- Home /
Issues with accessing properties in c#
I'm trying to implement an item system, And I want to change the values of certain variables in a bunch of scripts depending on the weapon the player has equipped.
I have a class, "Weapon", with properties of MaxDamage,AttackSpeed, and Range. (This class inherits from an Item class I made)
In another script, "PlayerCharacter", I have a property called EquipedWeapon, of type Weapon. Right now, since I don't have the equipment system set up yet, i just assisgned the variable EquipedWeapon references as a new Weapon(); using the default constructor.
In my attack script for the player, I'm trying to set the maxDamage in that script to the MaxDamage of the EquipedWeapon property, but I can't seem to get it to work properly.. I'm getting the Error: Object reference not set to an instance of an object. Does anyone know what's wrong?
Heres the code:
Assigning the equippedWeapon public class PlayerCharacter : MonoBehaviour {
public Weapon equipedWeapon;
private Weapon EquipedWeapon{
get { return equipedWeapon; }
set { equipedWeapon = value; }
}
// Use this for initialization
void Start () {
equipedWeapon = new Weapon();
}
And heres the attack script, Trying to reference the properties of the EquipedWeapon property:
public void adjustVars() {
PlayerCharacter pc = (PlayerCharacter)GetComponent("PlayerCharacter");
maxDamage = pc.EquipedWeapon.MaxDamage;
attackSpeed = pc.EquipedWeapon.AttackSpeed;
range = pc.EquipedWeapon.Range;
}
Does this make sense? Can anyone tell me what I'm doing wrong?
-Thanks
Answer by Kaivo · Jun 24, 2013 at 11:44 PM
Could it be that the GetComponent is not from the instanciated object? You should get a reference of the object on which the "PlayerCharacter" script is attached and perform the GetComponent from this object's reference. Maybe something like :
GameObject.FindWithTag("PlayerCharacter").GetComponent("PlayerCharacter");
or something along those lines. Also, instead of putting this in the fuction, make it a private variable of your class and call this line on Start(), so that you have to find it only one time.
Oh god I'm sorry! I feel quite stupid, It was just because I didn't attach the script to the player Character! I did at one point, but I closed unity without saving the scene..
Your answer made me realize this, so I will accept it!
Your answer
Follow this Question
Related Questions
Are properties variables? 1 Answer
Accessing class properties through getters & setters in editor mode 1 Answer
Character Equip Animation 0 Answers