Answers for "getcomponent"

C#
1

getcomponent

ur so stoopid u dum its eeeeeeez to use getcomponent jkust doo

Getcomponent<*A component to get*>().*the thing you need in the component* *100/= true/= false/ color.red
Posted by: Guest on January-06-2021
2

getcomponent c#

//First script 
public class Enemy : MonoBehaviour{
  public int health = 10;
  public void saySomething(){
    Debug.Log("Hi, i am an enemy.");
  } 
}
//Second script
//There is one thing though,
//if the script is located on another gameobject,
//which will be most likely, you have to somehow
//find that gameobject first. There are many ways of
//doing it, via raycast, collision,
//trigger, find by tag, find by gameobject etc.
//But i will use the simplest way to understand,
//that is declaring public GameObject in player script,
//which contains Enemy, and later you just drag and drop the
//gameobject in the inspector.
public class Player : MonoBehaviour{
  //Drag and drop gameobject with script Enemy in inspector
  GameObject enemyGameObject;
  void Start(){       
    //We get Enemy component - script
    //from public gameobject which contains this script
    Enemy enemyScript = enemyGameObject.GetComponent<Enemy>();
    //This will debug Enemy health is: 10  
    Debug.Log("Enemy health is:"+ enemyScript.health)  
      //This will debug "Hi, i am an enemy." 
      enemyScript.saySomething();  
  } 
}
Posted by: Guest on May-26-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
0

getcomponent

public Gameobject a; //this allows you to drag an object into a slot in the unity software
private transform b; //this is a variable that can only be assigned and altered in script

b = a.GetComponent<Transform>(); //this finds the transform component of 'a' and assigns that to 'b'
Posted by: Guest on June-22-2021

C# Answers by Framework

Browse Popular Code Answers by Language