Change GameObject from different script
In one script that i will call main i have a gameobject
public class main { public GameObject selectedUnit; }
how would i change what selectedUnit is from a script that was on a different object?
(also sorry if this is a dumb question im still new to unity and couldn't find an answer on youtube so am asking you folks)
Comment
Answer by Ossi101 · Jul 17, 2019 at 12:04 PM
You will need to have a reference to your "Main" script in the other object script.
public class MainScript: MonoBehaviour
{
public GameObject selectedUnit;
}
This OtherObject script will set MainScript's selectedUnit variable to whatever object has this script as a component.
public class OtherObject : MonoBehaviour
{
public MainScript mainScript = null;
private void Start()
{
mainScript.selectedUnit = gameObject;
}
}
Make sure you drag the object that has MainScript attached into the other object's MainScript variable in the inspector or you'll get an error. I hope this helps!