I am still fairly new to Unity and programming in general. I have been having trouble comparing information between objects and the object that I have attached a script to. I would like to access all of the information for an object if it has a particular script attached to it. Is there any specific way to have an object reference itself or is there a programming technique I should use to make sure an object holds onto that information?
you can get a reference to the gameobject running the script itself by
this.gameObject
to see if a GameObject has script x attached you should try to use GetComponent and it will retun null if there is no component of type x attached.
if (GetComponent(x) == null)
{
//no component of type x attached
]
else
{
//component is attached
}
To access components between objects, use the GameObject.GetComponent family of methods (see also GetComponentInChildren, along with GetComponents and GetComponentsInChildren, which return an array of those components, if there are multiple instances of a component attached to an object). Eg:
var myComponent : ScriptType = targetGameObject.GetComponent (ScriptType);
if (myComponent) {
//do things with myComponent
}
var myComponentArray : ScriptType[] = targetGameObject.GetComponents (ScriptType);
for (var component : ScriptType in myComponentArray) {
//Do something with an individual instance of that script.
}
Where "ScriptType" is the name of the script (or other component, like ParticleEmitter) you're looking for and "targetGameObject" is the GameObject you expect to have the component (for example, the "other" in an OnTriggerEnter or what have you). Remember GetComponents always returns something while GetComponent will return null if the script isn't attached to the object you're checking.