Answers for "unity get component"

C#
13

how to get component in unity c#

GetComponent<Rigidbody>(); //used to find component on character (rigid body can be changed)
GameObject.FindGameObjectWithTag("player"); //finds any game object in the scene with this tag
Posted by: Guest on July-03-2020
1

how to find a component in unity

//Say you want to find a BoxCollider in the button, you would find the Gameobject first
//Then you would get the component of "BoxCollider" from "Button"

GameObject Button = GameObject.Find("Button");
BoxCollider button = Button.GetComponent<BoxCollider>();
Posted by: Guest on March-17-2021
7

unity get component

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour
{
    void Start()
    {
    	// Since Unity  2019.2 you can use TryGetComponent to check
        // if an object has a component, it will not allocate GC in 
        // the editor if the object doesn't have one.
        if (TryGetComponent(out Rigidbody rigidFound))
        {
        	// Deactivate rigidbody
            rigidFound.enabled = false;
        }
        
		// For versions below 2019.2 you can do it this way:
        // Create a variable
        Rigidbody rigidFound = GetComponent<Rigidbody>();
        
        // If the 'Rigidbody' exist in the gameobject
        if(rigidFound != null)
        {
        	// Deactivate rigidbody
            rigidFound.enabled = false;
        }
	}
}
Posted by: Guest on April-27-2020

C# Answers by Framework

Browse Popular Code Answers by Language