除非在访问它的方法中分配变量,否则不分配变量
Variable not being assigned unless it is assigned within the method that accesses it
Sheep 继承自 Animal class.The 以下应调用 Sheep 的 Attack() 方法,这是一个显示 animalName 变量的 Debug.Log()。相反,Unity 什么都不显示。
如果我将 animalName 的声明移动到 Attack() 方法中,它会起作用,但出于某种原因,如果它位于 class 本身而不是被调用的方法中,它不会分配 animalName。
public class Test : MonoBehaviour {
public Animal Animal;
void Update () {
Animal.Attack();
}
}
这里是不起作用的 Animal 对象。
public class Sheep : Animal {
string animalName = "wot";
public override void Attack()
{
Debug.Log(animalName);
}
}
这里是绵羊继承自的动物class:
public abstract class Animal : MonoBehaviour {
public int hpMax;
public int power;
public int defense;
public int speed;
public string animalName ;
abstract public void Attack();
}
尝试更改您的 Sheep
class 使其看起来像这样:
public class Sheep : Animal {
public Sheep()
{
animalName = "wot";
}
public override void Attack()
{
Debug.Log(animalName);
}
}
Sheep 继承自 Animal class.The 以下应调用 Sheep 的 Attack() 方法,这是一个显示 animalName 变量的 Debug.Log()。相反,Unity 什么都不显示。
如果我将 animalName 的声明移动到 Attack() 方法中,它会起作用,但出于某种原因,如果它位于 class 本身而不是被调用的方法中,它不会分配 animalName。
public class Test : MonoBehaviour {
public Animal Animal;
void Update () {
Animal.Attack();
}
}
这里是不起作用的 Animal 对象。
public class Sheep : Animal {
string animalName = "wot";
public override void Attack()
{
Debug.Log(animalName);
}
}
这里是绵羊继承自的动物class:
public abstract class Animal : MonoBehaviour {
public int hpMax;
public int power;
public int defense;
public int speed;
public string animalName ;
abstract public void Attack();
}
尝试更改您的 Sheep
class 使其看起来像这样:
public class Sheep : Animal {
public Sheep()
{
animalName = "wot";
}
public override void Attack()
{
Debug.Log(animalName);
}
}