- Home /
Dynamically get variable from gameobject script
So I have an Object variable which at any given moment equals one of several scripts. In each of these scripts there is a variable with the same name and a different value. My goal is to get the variable from whatever script is assigned to this Object without making a million if statements. For example, here is what part of my code looks like:
if (shipname = default001) {
health = default001.health;
manager.barDisplay = health;
}
if (shipname = default002) {
health = default002.health;
manager.barDisplay = health;
}
The above code works, but there are a lot of those. Is there a way to do it without like a gazillion if statements? I have tried simply putting:
health = shipname.health;
manager.barDisplay = health;
but that just gives me an error saying "'UnityEngine.Object' does not contain a definition for 'health'"
Does anyone know how to make this work?
Answer by RyanRothweiler · Nov 23, 2014 at 12:16 AM
It sounds like you want to make your own class (which also creates a custom type). I might be interpreting your question wrong though.
So instead of having a new script for every ship. You just make a ship class. Make a new file which has (this is C# btw)
public class Ship: MonoBehaviour
{
public string shipName;
public int shipHealth;
}
So then just attach this script to every ship you have. Edit the values in the inspector per ship, or anywhere else. Then you can do something like.
public Ship shipAbout;
manager.barDisplay = shipAbout.shipHealth;
Maybe this this helps?
Your answer
Follow this Question
Related Questions
Cannot access class array in dynamically created object 1 Answer
Dynamic text on object 1 Answer
Where can I learn to do this? 1 Answer
RealTime Dynamic Modeling 6 Answers
Increase/Decrease Object Scale 1 Answer