0

I have instantiated a prefab in the scene that gets destroyed after 2 secs. I want to change its speed variable in its move script so that whenever it instantiate it has new speed.

2 Answers 2

4

The instantiate function returns the game object you created.

GameObject prefabObject = Instantiate(...);

Then you can obviously do something like

prefabObject.GetComponent<moveScript>().speed = 4;
Sign up to request clarification or add additional context in comments.

3 Comments

Don't ever name a variable gameObject as it is the name of variable used to access the GameObject this script script is attached to.
@CowNecromancer Yeah, that's what I have done, but I want to change the prefab in Runtime so that when it is Instantiated in runtime it follows the new set of properties (I want to bypass this process of assigning everytime it gets instantiated, I want to define once). and when ends I want prefab to return to its original state.
@NoorulainArain I'm not sure what you mean. Do you want it so the actual prefab itself changes to these new properties? because the only other way I can think of is to assign each variable. Could you try to be more specific? Also try to give a bit of an example of what you're trying to do. Like create a prefab of what?
0

You have not provided enough information, but I will try to answer.

Will this be done by another script or the Move script you have attached on the prefab?

If from the Move script then:

private void Awake()
{
    speed = MY_NEW_SPEED;
}

If from another script, then you first need to access the instantiated object and then its Move scripts. You have not provided enough information so I will assume you already have a reference to your instantiated object:

instantiatedObject.GetComponent<Move>().speed = MY_NEW_SPEED;

https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

2 Comments

I am going that already. I want to know if we can change prefab (Project panel) at runtime and return it to its old state when the game ends.
why don't you just change the prefab values then? if the values are going to be reverted back after the game ends then what is the point of having them and not having the ones you need from the start?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.