using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class find : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        MeshRenderer ms = GetComponent<MeshRenderer>();
        ms.renderingLayerMask = 2;
        ms.renderingLayerMask = 3;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

'Unity > C#' 카테고리의 다른 글

LayerChanger  (0) 2021.06.08
물체의 랜덤 스케일  (0) 2021.01.04
캐릭터 랜덤 애니메이션  (0) 2021.01.02
재미로 만들어보는 유니티(콘솔) 로또  (0) 2020.12.29
유리가 깨지는 연출  (0) 2020.12.15
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

#if UNITY_EDITOR // 빌드시 제외시키는 기능이다.

public class LayerChanger : EditorWindow
{
    [MenuItem("RHY/LayerChanger", false, priority: 1)]//메뉴생성


    static void ShowWindow()
    {
        // 생성되어있는 윈도우를 가져온다. 
        LayerChanger window = (LayerChanger)EditorWindow.GetWindow(typeof(LayerChanger));

    }


    void OnGUI()
    {

        if (GUI.Button(new Rect(50, 80, 180, 40), "LayerChanger"))
        {
            SkinnedMeshRenderer [] MeshR = FindObjectsOfType(typeof(SkinnedMeshRenderer)) as SkinnedMeshRenderer[]; //SkinnedMeshRenderer를 찾는다.

            List<GameObject> listGO = new List<GameObject>(); // 하나씩 찾는다.
            if (MeshR != null)
            {
                for (int i = 0; i < MeshR.Length; i++)
                    listGO.Add(MeshR[i].gameObject);
            }

            Selection.objects = listGO.ToArray(); // 선택하여준다.

            //  MeshR = GetComponentsInChildren<SkinnedMeshRenderer>();
            foreach (var meshRenderer in MeshR) //각각 물체에 레이어를 넣어준다
            {
                meshRenderer.renderingLayerMask = 1; // 첫번째 레이어 설정

                meshRenderer.renderingLayerMask |= 1 << 1; // 추가 레이어 설정
                
            }


        }
    }

}

#endif

'Unity > C#' 카테고리의 다른 글

renderingLayerMask Set  (0) 2022.06.03
물체의 랜덤 스케일  (0) 2021.01.04
캐릭터 랜덤 애니메이션  (0) 2021.01.02
재미로 만들어보는 유니티(콘솔) 로또  (0) 2020.12.29
유리가 깨지는 연출  (0) 2020.12.15

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NPC_Chair_Random : StateMachineBehaviour
{
    // OnStateEnter is called before OnStateEnter is called on any state inside this state machine
    //override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    
    //}

    // OnStateUpdate is called before OnStateUpdate is called on any state inside this state machine
    //override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    
    //}

    // OnStateExit is called before OnStateExit is called on any state inside this state machine
    //override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    
    //}

    // OnStateMove is called before OnStateMove is called on any state inside this state machine
    //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    
    //}

    // OnStateIK is called before OnStateIK is called on any state inside this state machine
    //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    
    //}

    // OnStateMachineEnter is called when entering a state machine via its Entry Node
    override public void OnStateMachineEnter(Animator animator, int stateMachinePathHash)
    {
        animator.SetInteger("MoveID", Random.Range(0, 2)); //""따옴표 때문에 에러가 나서 헤멤.
    }

    // OnStateMachineExit is called when exiting a state machine via its Exit Node
    //override public void OnStateMachineExit(Animator animator, int stateMachinePathHash)
    //{
    //    
    //}
}

'Unity > C#' 카테고리의 다른 글

LayerChanger  (0) 2021.06.08
물체의 랜덤 스케일  (0) 2021.01.04
재미로 만들어보는 유니티(콘솔) 로또  (0) 2020.12.29
유리가 깨지는 연출  (0) 2020.12.15
Sin, Cos, Tan  (0) 2020.12.15
{

	int[] array = new int[7];    
	public int[] GrobA;
	public int[] GrobB;

	int tru = 0;
    
    // Start is called before the first frame update
    void Start()
    {
	    AAA();
	    BBB();
	    CCC();
    }

	void AAA()
	{
		print("-------------start--------------");
		print("-------------45개랜덤--------------");
		for (int i = 1; i < array.Length ; )
        	{
			//array[i] = i;
				int result = Random.Range(1, 45);
				if(tru != result)
				{
					print(result);
					i =i+1;
				}

	        tru = result;
        }

	}
	
	void BBB()
	{
		print("-------------GrobA 랜덤--------------");
        
		for (int i = 1; i < array.Length ;)
		{
			//array[i] = i;

            
			int result = Random.Range(1, GrobA.Length);

			if(tru != result)
			{
				print(GrobA[result]);
				i =i+1;
			}
               
			tru = result;

		}
		
	}

    
	void CCC()
	{
		print("-------------GrobB 랜덤--------------");
        
        
		for (int i = 1; i < array.Length ; )
		{
			//array[i] = i;

            
			int result = Random.Range(1, GrobB.Length);

			if(tru != result)
			{
				print(GrobB[result]);
				i =i+1;
			}
               
			tru = result;

		}  
		
	}

}

 

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class TEST_Num : MonoBehaviour
{
    private int[] numbers = Enumerable.Range(1, 45).ToArray();
    private List<int> selectedNumbers = new List<int>();

    public int SetNumber = 1;

    [SerializeField]
    private int[] desiredNumbers = new int[] { };

    private void Start()
    {
        SelectNumbers();
        DisplaySelectedNumbers();
    }

    private void SelectNumbers()
    {
        System.Random random = new System.Random();

        while (selectedNumbers.Contains(0) || selectedNumbers.Count < 6)
        {
            selectedNumbers.Clear();

            for (int i = 0; i < Math.Min(desiredNumbers.Length, SetNumber); i++)
            {
                int requiredNumberIndex = Array.IndexOf(numbers, desiredNumbers[i]);

                if (random.NextDouble() < 0.7)
                {
                    selectedNumbers.Add(desiredNumbers[i]);
                    numbers[requiredNumberIndex] = numbers[numbers.Length - i - 1];
                }
            }

            for (int i = Math.Min(desiredNumbers.Length, 3); i < 6 && selectedNumbers.Count < 6;)
            {
                int index = random.Next(0, numbers.Length - i);
                int selectedNumber = numbers[index];

                if (selectedNumber == 0)
                {
                    continue;
                }

                selectedNumbers.Add(selectedNumber);
                numbers[index] = numbers[numbers.Length - i - 1];
                i++;
            }
        }
    }

    private void DisplaySelectedNumbers()
    {
        string result = string.Join(", ", selectedNumbers.OrderBy(x => x));
        Debug.Log(result);
    }
}

'Unity > C#' 카테고리의 다른 글

물체의 랜덤 스케일  (0) 2021.01.04
캐릭터 랜덤 애니메이션  (0) 2021.01.02
유리가 깨지는 연출  (0) 2020.12.15
Sin, Cos, Tan  (0) 2020.12.15
물체를 회전하고 상하 반복움직임.  (0) 2020.12.11

자주 헛갈려서 그림으로 정리해봤습니다.

'Unity > C#' 카테고리의 다른 글

재미로 만들어보는 유니티(콘솔) 로또  (0) 2020.12.29
유리가 깨지는 연출  (0) 2020.12.15
물체를 회전하고 상하 반복움직임.  (0) 2020.12.11
텍스쳐 애니메이션 타일셋  (0) 2020.12.11
C# 기초 기억창고2  (0) 2020.12.11

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class AnimateTiledTexture : MonoBehaviour
{
    public int _columns = 2;                        // The number of columns of the texture
    public int _rows = 2;                           // The number of rows of the texture
    public Vector2 _scale = new Vector3(1f, 1f);    // Scale the texture. This must be a non-zero number. negative scale flips the image
    public Vector2 _offset = Vector2.zero;          // You can use this if you do not want the texture centered. (These are very small numbers .001)
    public Vector2 _buffer = Vector2.zero;          // You can use this to buffer frames to hide unwanted grid lines or artifacts
    public float _framesPerSecond = 10f;            // Frames per second that you want to texture to play at
    public bool _playOnce = false;                  // Enable this if you want the animation to only play one time
    public bool _disableUponCompletion = false;     // Enable this if you want the texture to disable the renderer when it is finished playing
    public bool _enableEvents = false;              // Enable this if you want to register an event that fires when the animation is finished playing
    public bool _playOnEnable = true;               // The animation will play when the object is enabled
    public bool _newMaterialInstance = false;       // Set this to true if you want to create a new material instance
 
    private int _index = 0;                         // Keeps track of the current frame 
    private Vector2 _textureSize = Vector2.zero;    // Keeps track of the texture scale 
    private Material _materialInstance = null;      // Material instance of the material we create (if needed)
    private bool _hasMaterialInstance = false;      // A flag so we know if we have a material instance we need to clean up (better than a null check i think)
    private bool _isPlaying = false;                // A flag to determine if the animation is currently playing
 
 
    public delegate void VoidEvent();               // The Event delegate
    private List<VoidEvent> _voidEventCallbackList; // A list of functions we need to call if events are enabled
 
    // Use this function to register your callback function with this script
    public void RegisterCallback(VoidEvent cbFunction)
    {
        // If events are enabled, add the callback function to the event list
        if (_enableEvents)
            _voidEventCallbackList.Add(cbFunction);
        else
            Debug.LogWarning("AnimateTiledTexture: You are attempting to register a callback but the events of this object are not enabled!");
    }
 
    // Use this function to unregister a callback function with this script
    public void UnRegisterCallback(VoidEvent cbFunction)
    {
        // If events are enabled, unregister the callback function from the event list
        if (_enableEvents)
            _voidEventCallbackList.Remove(cbFunction);
        else
            Debug.LogWarning("AnimateTiledTexture: You are attempting to un-register a callback but the events of this object are not enabled!");
    }
 
    public void Play()
    {
        // If the animation is playing, stop it
        if (_isPlaying)
        {
            StopCoroutine("updateTiling");
            _isPlaying = false;
        }
        // Make sure the renderer is enabled
        GetComponent<Renderer>().enabled = true;
 
        //Because of the way textures calculate the y value, we need to start at the max y value
        _index = _columns;
 
        // Start the update tiling coroutine
        StartCoroutine(updateTiling());
    }
 
    public void ChangeMaterial(Material newMaterial, bool newInstance = false)
    {
        if (newInstance)
        {
            // First check our material instance, if we already have a material instance
            // and we want to create a new one, we need to clean up the old one
            if (_hasMaterialInstance)
                Object.Destroy(GetComponent<Renderer>().sharedMaterial);
 
            // create the new material
            _materialInstance = new Material(newMaterial);
 
            // Assign it to the renderer
            GetComponent<Renderer>().sharedMaterial = _materialInstance;
 
            // Set the flag
            _hasMaterialInstance = true;
        }
        else // if we dont have create a new instance, just assign the texture
            GetComponent<Renderer>().sharedMaterial = newMaterial;        
 
        // We need to recalc the texture size (since different material = possible different texture)
        CalcTextureSize();
 
        // Assign the new texture size
        GetComponent<Renderer>().sharedMaterial.SetTextureScale("_MainTex", _textureSize);
    }
 
    private void Awake()
    {
        // Allocate memory for the events, if needed
        if (_enableEvents)
            _voidEventCallbackList = new List<VoidEvent>();
 
        //Create the material instance, if needed. else, just use this function to recalc the texture size
        ChangeMaterial(GetComponent<Renderer>().sharedMaterial, _newMaterialInstance);
    }
 
    private void OnDestroy()
    {
        // If we wanted new material instances, we need to destroy the material
        if (_hasMaterialInstance)
        {
            Object.Destroy(GetComponent<Renderer>().sharedMaterial);
            _hasMaterialInstance = false;
        }
    }
 
    // Handles all event triggers to callback functions
    private void HandleCallbacks(List<VoidEvent> cbList)
    {
        // For now simply loop through them all and call yet.
        for (int i = 0; i < cbList.Count; ++i)
            cbList[i]();
    }
 
    private void OnEnable()
    {
 
       CalcTextureSize();
 
        if (_playOnEnable)
            Play();
    }
 
    private void CalcTextureSize()
    {
        //set the tile size of the texture (in UV units), based on the rows and columns
        _textureSize = new Vector2(1f / _columns, 1f / _rows);
 
        // Add in the scale
        _textureSize.x = _textureSize.x / _scale.x;
        _textureSize.y = _textureSize.y / _scale.y;
 
        // Buffer some of the image out (removes gridlines and stufF)
        _textureSize -= _buffer;
    }
 
    // The main update function of this script
    private IEnumerator updateTiling()
    {
        _isPlaying = true;
 
        // This is the max number of frames
        int checkAgainst = (_rows * _columns);
 
        while (true)
        {
            // If we are at the last frame, we need to either loop or break out of the loop
            if (_index >= checkAgainst)
            {
                _index = 0;  // Reset the index
 
                // If we only want to play the texture one time
                if (_playOnce)
                {
                    if (checkAgainst == _columns)
                    {
                        // We are done with the coroutine. Fire the event, if needed
                        if(_enableEvents)
                            HandleCallbacks(_voidEventCallbackList);
 
                        if (_disableUponCompletion)
                            gameObject.GetComponent<Renderer>().enabled = false;
 
                        // turn off the isplaying flag
                        _isPlaying = false;
 
                        // Break out of the loop, we are finished
                        yield break;
                    }
                    else
                        checkAgainst = _columns;    // We need to loop through one more row
                }
 
            }
 
            // Apply the offset in order to move to the next frame
            ApplyOffset();
 
            //Increment the index
            _index++;
 
            // Wait a time before we move to the next frame. Note, this gives unexpected results on mobile devices
            yield return new WaitForSeconds(1f / _framesPerSecond);
        }        
    }
 
    private void ApplyOffset()
    {
        //split into x and y indexes. calculate the new offsets
        Vector2 offset = new Vector2((float)_index / _columns - (_index / _columns), //x index
                                      1 - ((_index / _columns) / (float)_rows));    //y index
 
        // Reset the y offset, if needed
        if (offset.y == 1)
            offset.y = 0.0f;
 
        // If we have scaled the texture, we need to reposition the texture to the center of the object
        offset.x += ((1f / _columns) - _textureSize.x) / 2.0f;
        offset.y += ((1f / _rows) - _textureSize.y) / 2.0f;
 
        // Add an additional offset if the user does not want the texture centered
        offset.x += _offset.x;
        offset.y += _offset.y;
 
        // Update the material
        GetComponent<Renderer>().sharedMaterial.SetTextureOffset("_MainTex", offset);
    }
}

관중용으로 썼었는데, 어디서 구했는지 기억이 안나네요. 너무 오래전이라..

'Unity > C#' 카테고리의 다른 글

Sin, Cos, Tan  (0) 2020.12.15
물체를 회전하고 상하 반복움직임.  (0) 2020.12.11
C# 기초 기억창고2  (0) 2020.12.11
텍스쳐를 자동으로 설정해봅시다.  (0) 2020.12.06
유니티의 Object 이해  (0) 2020.12.06

컬렉션

ArrayList

ArrayList arrayL = new ArrayList();
void Start(){
	arrayL.Add(1); //추가하기
	arrayL.Add(3);
    	arrayL.Add("list");
    	arrayL.Add("fun");
    
    	arrayL.Remove(list); //list를 지움.
        arrayL.RemoveAt(2); // 3번째 add된것을 지움.
        arrayL.RemoveRange(0,2) // 0-2까지 범위를 지움.
        arrayL[0] = "tt";//0번 인덱스를 바꾸는것.
    
    print(arrayLsit.Count);
    
    for(int i =0; 1 <arrayL.Count; i++)
    {
    	print(arrayL[i];
    }
    
}

List =  정수형, 문자형등 형식을 정해서 넣어서 사용하므로 ArrayList보다 성능이 더 좋다고 할수 있다.

 

HashTable =  특정키값을 정해서 리스트를 만드는 기능이다. [만수(특정값 , 10000)]

Dictionary =  HashTable과 유사하고 List처럼 정해진 형식을 사용한다.

 

Queue = 순서대로 값을 넣고 순서대로 값을 빼내서 없앨때 사용된다.

    Queue<int> qqu = new Queue<int>();

    void Start()
    {
        qqu.Enqueue(1);
        qqu.Enqueue(3);
        qqu.Enqueue(5);

        if (qqu.Count != 0)// 아무것도 없을때 에러가 나지 않게 if를 넣어준다.
            print(qqu.Dequeue());
        if (qqu.Count != 0)
            print(qqu.Dequeue());
        if (qqu.Count != 0) 
            print(qqu.Dequeue());
    }

 

Stack= 순서대로 값을 넣고 반대순서대로 값을 없앨때 사용된다.(젠가는 위로 쌓아서 위에서 부터 제거한다.)

    Stack<int> SST = new Stack<int>();

    void Start()
    {
        SST.Push(1);
        SST.Push(7);
        SST.Push(3);


        print(SST.Pop());
        print(SST.Pop());
        print(SST.Pop());

    }

'Unity > C#' 카테고리의 다른 글

물체를 회전하고 상하 반복움직임.  (0) 2020.12.11
텍스쳐 애니메이션 타일셋  (0) 2020.12.11
텍스쳐를 자동으로 설정해봅시다.  (0) 2020.12.06
유니티의 Object 이해  (0) 2020.12.06
Scene 재시작  (0) 2020.11.21