#Accessing another variable from a script that is on a different gameobject

1 messages · Page 1 of 1 (latest)

serene bluffBOT
#

How to get a reference

"How do I access a variable from another script?" is usually one of the first questions we ask when learning Unity. Whether you are C# beginner or a C# professional, understanding the way Unity does things differently can be confusing.

🌳 If the objects are already present in the scene hierarchy...
... then you can use the SerializeField attribute on a field, and assign it by dragging the object which has the script you want to access onto the field slot. This also works if the two scripts are on the same object.

[SerializeField] private SomeScript someScript;

prefab If the objects are instantiated prefabs...
... then you can use a form of injection after you call Instantiate:
SomeScript.cs

public GameManager TheManager { get; set; }

GameManager.cs

var clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().TheManager = this;
valid fossil
#

static var

#

script a: public static speed;

#

script b: scripta.speed = 50;

#

idk

true raven
#

anyone know how to fix?

valid fossil
#

screenshot ur inspector

#

u not attach object to variable

#

maybe

stiff compass
# true raven

// stored variable

private TestScript testScript;

private void Awake() 
{
  testScript = GetComponent<TestScript>();
  // or whatever you need to do to get component
}

// manually set

// populate in inspector
[SerializeField] private TestScript testScript;
gleaming fox
swift seal
#

Yeah that's just horrible advice

#

404 Good practices not found

valid fossil
#

Im just learn unity 3 week ago ._.

#

Thx 👍

true raven
#

how do i delete this post?

valid fossil