Answers for "unity get component by name"

3

unity find gameobject by name

GameObject enemy = GameObject.Find("enemy");
Posted by: Guest on October-25-2020
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
1

unity get object by name

function Update() {    var enemy : GameObject = GameObject.Find("enemy");    //perform operations on enemy here}
Posted by: Guest on October-28-2020

Browse Popular Code Answers by Language