- Home /
Multiple objects, same script, different values
I'm trying to make a farm game where it's possible to plant three different kinds of plants. They all act the same but they have different values (for example: they take longer/shorter to grow, different sprites, give more money etc.) Would I be able to implement this in the same script? That when a certain button is clicked, the fitting values for that kind of plant will be added to the script? Hope you can help me.
Answer by MerryAce123 · Sep 29, 2015 at 09:05 PM
This is actually what public variables do for you. On the start of your script you declare your variables which will have your changable values. Then you just work with the variables for the rest of the script. When you assign the script to multiple objects you can just set those values from the inspector or you can make some interactions inside the game which will set the values for you. Here is an example:
public float growTime;
public float size;
public float price;
// whatever else you need...
void Update(){
//And here you just work with your variables instead of specific numbers
}
If you want to set your variables from somewhere else, like you click a button or press a key you just create your plant and assign the values by using GetComponent... Here is an example how something like a "Farm manager" could look like:
public GameObject plant;
void Update() {
if(Input.GetKeyDown("s")){
GameObject g = Instantiate(plant, transform.position, Quaternion.identity) as GameObject;
g.GetComponent<TheNameOfYourPlantScript>().growTime = 5;
}
}
You create a prefab and put your plant object inside. Then you assign that prefab into the plant variable which will store the prefab. The if certain action happens like you press or click something we instantiate it, you can swap that transform.position for any Vector3 and then the instantiated object is stored into a "g" variable. The we take the plant script from our "g" variable and fill in any value we want.
Answer by Krunal_vasundhara · Jul 24, 2017 at 05:37 AM
I am use it but it still shows the null exception error in unity.
Your answer
![](https://koobas.hobune.stream/wayback/20220612035454im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
edit values for multiple objects concurrently 1 Answer
Same script on multiple objects. 2 Answers
how to pass values between objects in C# 2 Answers
Change materials of connecting objects 0 Answers
Swapping Objects 3 Answers