Prefabs and public variables
I've been researching this for days and just don't seem to understand. So, I'm reaching out to see if anyone can explain it to me in a way that "clicks."
I have a single-scene game, which has dynamically generated levels and a LevelManager that sets certain variables like enemy spawn rate, background, etc.
I'm trying to make a prefab gameobject that acts as a gust of wind and instantiates various other prefabs of leaves as it moves below the screen, tossing them in the air. These leaves act as hits on the player and I'd like to use the LevelManager to change variables on the gust prefab and leaf prefabs to change the height, amount, and "swirl" of them.
As prefabs, this seems impossible. I'm not sure why I can't change the public variables on the scripts in these prefabs onclick through the LevelManager.
I guess I could look into other ways of making this effect; but, I'm curious if I'm just missing things conceptually, as I am quite new to this.
All the best and many thanks.
Hi - to change the public variables in the scripts attached to prefabs, you need a reference to the actual script belonging to the prefab. Then you can reference the script's public variables like: SomeScript script; script.publicVariable = blah;
Answer by mskaarup · Jan 06, 2019 at 05:35 AM
You can get a reference to the script of a instance of a prefab using the following: Lets assume you have a reference to a newly Instantiated leaf from your prefab; we'll call it newLeaf
. Now, you want to get a reference to the script attached to the instance: LeafScript leafScript = newLeaf.GetComponent<LeafScript>();
Where "LeafScript" is the name of the script attached to the prefab.
You can now access variables and functions within that specific instance's script using leafScript.leafVariable = someValue
Your answer
Follow this Question
Related Questions
Prefabs not instantiating after build 0 Answers
Prefab disapeared 0 Answers
How to get the camera to follow a prefab? 2 Answers
Unity 2018.3 New prefab system How do I get rid of it? 1 Answer
Prefabs getting deleted in all scenes! 0 Answers