Skip to content

Instantly share code, notes, and snippets.

@mathiassoeholm
Last active May 27, 2024 16:35
Show Gist options
  • Select an option

  • Save mathiassoeholm/6744344 to your computer and use it in GitHub Desktop.

Select an option

Save mathiassoeholm/6744344 to your computer and use it in GitHub Desktop.
Example of how to access another GameObject's component
using UnityEngine;
public class GetComponentExample : MonoBehaviour
{
// First we need a reference to the other gameobject
// You can make a public field and assign a prefab in the inspector
public GameObject somePrefab;
// Or you can search for a gameobject and assign it to a variable
private GameObject gameObjectFoundBySearch;
void Start()
{
// You can find a gameobject by name
gameObjectFoundBySearch = GameObject.Find("Sphere");
// Or you can find it using the gameobjects tag
gameObjectFoundBySearch = GameObject.FindGameObjectWithTag("Tag");
// Tip: Don't use GameObject.Find or GameObject.FindGameObjectWithTag in Update since
// it's a heavy operation that scales with the amount of gameobects you have in the scene.
// Call it in start and save the reference in a member variable.
}
void Update()
{
// Now to acces a component on the gameobject,
// simply use the generic GetComponent method
TypeOfComponentGoesHere component = gameObjectFoundBySearch.GetComponent<TypeOfComponentGoesHere>();
// Tip: You can also use GetComponent in Start() and save a reference to the component
// in a member variable, so GetComponent isn't called every frame. This is called caching
// the component and is a very good practice!
// You can now use the public methods etc. on the component of the gameobject
component.DoStuff();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment