- Home /
Difference between a script in the scene and in instantiated
I have a script about GUIText.
public GUIText Enemyhealth;
private int EnemyH = 300;
private float distance = 2f;
Start {
Enemyhealth.text = " " + EnemyH;
}
Update {
if (Vector.Distance(transform.position, Vector.zero) < distance)
{
EnemyH = EnemyH - 50;
Enemyhealth.text = " " + EnemyH;
}
And it works perfectly - when both Enemyhealth ( GUIText object ) and object ( to which the script is attached to ) are on the scene.
But when i try to simply add "GUIText EnemyHealth = Instantiate ( Enemyhealth ) as GUIText;" trying to actually instantiate both GUIText and the object ( to which script is attached to ), it don't work.
It shows GUIText , but with a state from the last play before. If the last time i played it was 250, then only the next time i play it shows 250.
And it don't change the value in the game itself. If 250 should become 200, it stills shows 250, while in prefab it actually changed to 200. But the change itself will be shown only the next time i play. Without changing it in play mode at all.
So, as i said, it works perfectly when both GUIText object and the object ( to which scrpit is attached to ) are in the scene, but it's broken when they are instantiated. Why?
Answer by thepenguinmaster · Dec 10, 2014 at 06:40 PM
To get a reference to the script you will want to do the following:
instantiate as a gameobject gameobject.getcomponent
I had the same problem at one point. This is just psuedo code, but you have all of the parts there, you just need to arrange it differently, and when instantiating, get the game object, and then pull the script component out of the newly created gameobject. from there you can update the values in Enemyhealth.
Not sure if this helps, but from what I understand of your code and question, this may solve the problem.
Explain it a bit more. I need to create a script in the scene, and then GetComponent ( this script ) from an instantiated object?
Anyway i think i've founded a solution. I've created empty object, attached a sript to it ( that changes value ), created the GUIText object in the scene and dragged it to the script ( in the scene, under empty gameobject ). Added a collider to it ( the same size as the main object that triggers changes ). And just made the main object ( in main object's script) to become parent of this empty object in the scene. So empty object with script moves with the main object, having the same size of collider. The thing is - i don't need to instantiate nor the script nor the enemy health GUIText object, because there are already there in the scene, just beco$$anonymous$$g child of my instantiated main object :D
Your answer
Follow this Question
Related Questions
Instantiating GUI text after 2nd object is destroyed 1 Answer
Detect Text in GUI; Print 1 Answer
GUI text font change 3 Answers
Limit on GUI Components? 0 Answers
Unity GUI text displaying as noise 1 Answer