I am trying to make a few objects and classes interact. I have two classes. Code is similar. But in class Building_main
after object is initialized in Start() I can reuse it in functions and in class House_main
I can not (object is null). class Building_main
is a child of class House_main
.
What am I doing wrong?
First class :
public class Building_main : MonoBehaviour {
public string owner;
public string producedGoodName;
private Building_goods goods;
private House_main house;
void Start () {
goods = this.transform.Find("Building_goods").GetComponent<Building_goods>();
house = this.transform.parent.gameObject.GetComponent<House_main> ();
UpdateHouseInfo ();
}
void UpdateHouseInfo () {
// reusing objs (house, goods) no error
house.UpdateGoodInfo (goods.GetGoodByName("sword"), "sword");
}
Second class :
public class House_main : MonoBehaviour {
public string owner;
private House_goods goods;
void Start () {
// obj (goods) is not null
goods = this.transform.Find("House_goods").GetComponent<House_goods>();
// i can use
// goods.AddAmountToGoodByName (value, name);
}
public void UpdateGoodInfo (int value, string name) {
// obj (goods) is null
goods.AddAmountToGoodByName (value, name);
}
}
Looks like my child class ( class Building_main
) Start() function is executing before parent class ( class House_main
) Start() function.
So in class House_main
object goods
is not yet assigned when I am calling function UpdateGoodInfo
, because I am calling it using class Building_main
Start()
`class Building_main {
Start() {
UpdateHouseInfo ();
}
}`
Didn't know this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.