我有课
ProtagonistActor
。我里面有一个公共吸气剂GetActorState
.
在不同的班级
InputManager
我有:
ProtagonistActor _protagonistActor;
ActorState _actorState;
private void Awake()
{
_protagonistActor = GetComponent<ProtagonistActor>();
_actorState = _protagonistActor._actorState;
}
void OnJumpEvent()
{
Debug.Log($"Comparingggggggggg {_protagonistActor._actorState.Equals(_actorState)} {_protagonistActor._actorState == _actorState}");
}
我期待日志打印 True 但它正在打印 False 两者。
这怎么可能?
GetComponent<ProtagonistActor>().GetSome...
getter 返回一个新的引用吗?
我事件打印出哈希码,它们显示不同的值,如何?
Comparingggggggggg False False 1301530776 -256054432
详细代码示例:
[Serializable]
public class ActorState
{
public int tempP;
}
public class ProtagonistActor: MonoBehaviour // Attached to gameobject
{
[SerializeField]
public ActorState _actorState;
private void Awake()
{
InitiateActorState();
}
void InitiateActorState()
{
_actorState = new ActorState();
}
}
public class Test2: MonoBehaviour //Attached to Gameobject Player
{
private ProtagonistActor _protagonistActor;
private ActorState _actorState;
private void Awake()
{
_protagonistActor = GetComponent<ProtagonistActor>();
_protagonistActor._actorState.tempP = 90;
_actorState = _protagonistActor._actorState;
}
void OnMyJump()
{
Debug.Log($"Comparingggggggggg {_protagonistActor._actorState.tempP} {_actorState.tempP} {_protagonistActor._actorState.Equals(_actorState)} {_protagonistActor._actorState == _actorState} {_protagonistActor._actorState.GetHashCode()} {_actorState.GetHashCode()}");
}
}
输出
Comparingggggggggg 0 90 False False 744599944 781808744
检查方法的调用顺序。您可以在每个方法中使用简单的
Debug.Log
来实现。
看来你测试的
Awake
方法比你的Awake
类的ProtagonistActor
更早调用。在这种情况下,你会有这样的逻辑:
Awake
在测试中,缓存值为_actorState
,改变里面的参数_actorState
Awake
在ProtagonistActor
类中,调用InitiateActorState
方法并创建ActorState
类的全新实例,默认值为0.