Its a “shield” gameobject that is instantiated through a controller script and destroys itself after a certain time. Im trying to access this bool in a health manager so while the prefab exists a bool in that script is also set to true. It seems that the traditional GetComponent<> doesnt work on prefabs (clones)?
With prefabs you want to access this in a certain way. GetComponent on the prefab should work but I would do it this way. When instantiating the prefab you can also assign it to an object, as shown here.
GameObject shield = Instantiate(prefab, Vector3.Zero, Quaternion.identity) as GameObject;
The reason we write ‘as GameObject’ or alternatively ‘(GameObject) Instaniate();’ is to convert the Object type given by Instantiate into a GameObject type in which we can use all of our regular stuff you would expect from a GameObject.
@DaedricWolf19 , shield will be typed as GameObject, so that won’t compile. Casting to GameObject is also not neccessary from 5.5 and forward, as there’s a generic overload.
@gfvanillah , could you post the code where you’re trying to access the script? It should work as usual.
public bool shielding = true; // needs to be public to access from other scripts
public float lifeTime;
void update()
{
shielding = true; // every frame you are resetting this to true, I don't think you need to do this.
lifeTime -=Time.Delta.time
if lifeTime <= 0
{
destroy(gameObject)
}
}
from a second script that would access the bool you need to something like GameObject shield = GameObject.Find(“name of gameObject that is the shield”);
Debug.Log(shield.GetComponent<“name of the scipt that stores shielding bool”>().shielding);
if(shield.GetComponent<“name of the scipt that stores shielding bool”>().shielding)
{
//do stuff
}
@Baste I know it is bad practice. but for a noob. it’s easier to understand so that’s why I use in the forums. I took me time to figure out that I need to create a variable and do the getComponent in the Start() or Awake()