access to public methods of instance
I am trying to read variable from instance of my class A.
// Class A
public class A: MonoBehaviour {
private float age;
Start () {
age = Time.time;
}
public float getAge() {
return age;
}
}
And I want to use it in class B to get oldest instance, that is triggering with my object.
// class B
public class B: MonoBehaviour {
private List<GameObject> myObjectList;
void Start () {
myObjectList = new List <GameObject>();
}
void OnTriggerEnter(Collider other) {
myObjectList.Add(other.gameObject);
}
void Update () {
foreach (GameObject myObject in myObjectList){
// here is my problem. I have references to instances, that I need, but I don´t know how to elegantly access to their variable "getAge()"
}
}
Comment
Best Answer
Answer by Denvery · Oct 09, 2015 at 10:18 PM
Hello!
I think you can use this way (if you're sure that all objects in myObjectList have MonoBehaviour A):
foreach (GameObject myObject in myObjectList)
{
myObject.GetComponent<A>().getAge();
}
Or, even this way:
public class B: MonoBehaviour
{
private List<A> myObjectList;
void Start () {
myObjectList = new List <A>();
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.GetComponent<A>() != null)
{
myObjectList.Add(other.gameObject.GetComponent<A>());
}
}
void Update () {
foreach (A myObject in myObjectList){
myObject.getAge();
}
}