- Home /
Duplicate Question
Getting a variable from an object
I have several objects that run on the same script. The idea is that they both count down and then attack each other (though for now they just attack whatever monster is second in the array). using UnityEngine; using System.Collections;
public class MonsterAI : MonoBehaviour
{
public string name = "NoName";
public float hp = 100f;
public float attack = 10f;
public float speed = 10f;
public float team = 1f;
float action_bar = 100f;
public GameObject[] target;
void Start()
{
}
void Update()
{
//ticking down their action bar
if (action_bar > 0f)
{
action_bar -= speed * Time.deltaTime;
}
else
{
target = GameObject.FindGameObjectsWithTag("Monster");
Attack (target[1]);
Debug.Log (name + " has ended their turn.");
action_bar = 100f;
}
}
//functions
void Attack(GameObject target)
{
Debug.Log (name + " attacks " + target.name + ".");
}
}
The problem is in Debug.Log (name + " attacks " + target.name + "."); the second name it gives is that of the object, not the variable within the object. One has the variable named "Steve" and the other "Bob" but both object's names are "Monster", so it says "Steve attacks Monster." when I would like it to say "Steve attacks Bob.". How do you get a variable from an object passed into a function like that?
Create a function that returns the string, like,
Player.getName();
function getName()
{
return this.name;
}
So there is no way to pull a public variable from an object without a function within the other object?
Answer by robertbu · Sep 29, 2013 at 04:45 AM
Scripts are components, so you will need to use GetComponent() to get access to the MonsterAI script and the 'name' in that script:
var monsterName = target.GetComponent(MonsterAI).name;
Then your output:
Debug.Log (name + " attacks " + monsterName + ".");
Here are links concerning accessing other game objects and components:
http://docs-jp.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
http://docs-jp.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Components.html