- Home /
So I'm trying to reference a rigidbody inside a class for all my enemies and NPCs, like so. However, it throws up this error. How do I fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Creature
{
public int MaxHealth;
public int currentHealth;
public float MovementSpeed;
public int Damage;
public bool[] canMove;
public string[] tagVulnerable;
public Rigidbody2D rb;
public Animator animator;
public GameObject gameObject;
public bool isAttacking;
public bool isCharging;
public bool isHurt;
public Creature(int mHealth, float moveSpeed, int dmg, Rigidbody2D rbody, Animator amor, GameObject gameObj) {
MaxHealth = mHealth;
MovementSpeed = moveSpeed;
Damage = dmg;
rb = rbody;
animator = amor;
gameObject = gameObj;
}
public class Sentient {
public int MaxMana;
public int currentMana;
public bool useMana(int mana) {
if(currentMana > mana) {
currentMana -= mana;
return true;
}
else {
return false;
}
}
public Sentient(int mMana, int cMana) {
MaxMana = mMana;
currentMana = cMana;
}
}
public void takeDamage(int damage) {
currentHealth -= damage;
if(currentHealth <= 0) {
die();
}
}
public void move(float xMagnitude, float yMagnitude) {
bool willMove = true;
Vector2 vector = new Vector2(xMagnitude, yMagnitude);
for(int i = 0; i < canMove.Length; i++) {
if(canMove[i] == false) {
willMove = false;
break;
}
}
if(willMove) {
rb.MovePosition(rb.position + vector * MovementSpeed * Time.fixedDeltaTime);
}
}
public void die() {
Object.Destroy(gameObject);
}
public bool isVulnerable(string Tag) {
bool vulnerable = false;
for(int i = 0; i < tagVulnerable.Length; i++) {
if(tagVulnerable[i] == Tag) {
vulnerable = true;
break;
}
}
return vulnerable;
}
}
So that's my code for my class Creature, and my sub-class Sentient. What I want to do is to be be able to access the rigidbody, animator and gameobject of any creature code I write, but Unity throws up this error: CS0236: A field initializer cannot reference the non-static field, method, or property 'Component.gameObject' That error crops up for the animator and the rigidbody as well. Any way for me to reference the rigidbody, animator and gameobject in a class and get around this?
Your answer
![](https://koobas.hobune.stream/wayback/20220613012054im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can I create boundaries around my level without using box colliders? 3 Answers
2018.2.17 OnTriggerEnter2D not working 1 Answer
Prevent gameobjects from overlapping - 2D 0 Answers
How do I convert this into Fixed Update for physics and Update for inputs? 0 Answers
Unity2D Can't implement wall jumping ! 0 Answers