- Home /
Serialized class, Instances and access
I'm trying to implement integrated weapons controller and a simple inventory.
In the MainCharacterController.cs I've Got:
[System.Serializable]
public class Inventory
{
public int ammo1 = 100;
public int ammo2 = 50;
public int withdrawAmmo(string _type, _qnt)
{
//do stuff and return qnt
}
}
public class MainCharacterController : MonoBehaviour
{
//among other things....
public Inventory _inv;
}
Inside **WeaponController.cs** Ive got:
public class WeaponController : MonoBehaviour
{
MainCharacterController _main;
Inventory _inv;
void Start()
{
_main = transform.GetComponent<MainCharacterController>();
_inv = _main._inv;
}
}
and the _inv from weaponcontroller is giving nullReferenceException.
From what i've been thinking it must be about intance of this serialized class serving as inventory.
If anyone knows how to solve it ou a better way to implement this, help me please!
Thanks.
Hi! Can you give us the line? (In the code above!) A null reference is thrown when you try to use a null reference. The only place where we can see you use a reference is at line 11 of your second part. Can you check is _main is not null?
You're right. Seems a silly mistake. I instantiate a weapon and add it to the main character hierarchy. But the weapon code tries to find the component on itself. Working on it.
Pulled it trough. $$anonymous$$ikilo was right about the missing reference of the $$anonymous$$ainCharacterController component.
Answer by Mikilo · Feb 27, 2013 at 09:47 PM
So, if your transform doesn't find MainCharacterController, try this.GetComponentInChildren(). That would fix your problem.
Good luck.
actually the component is on top hierarchy parent. I've build a recursive method to reach top parent and then look for component.
Your answer
Follow this Question
Related Questions
Implementing an Item system - Defining Items 1 Answer
Getting any type in Unity Inspector 1 Answer
asset is emty on enering play mode 1 Answer
C#: Serialize a class as Field 1 Answer
Dictionary serialization woes 2 Answers