Unity GetComponent<>().GetObject 返回 false 与 Equals

问题描述 投票:0回答:1

我有课

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
c# unity3d
1个回答
0
投票

检查方法的调用顺序。您可以在每个方法中使用简单的

Debug.Log
来实现。

看来你测试的

Awake
方法比你的
Awake
类的
ProtagonistActor
更早调用。在这种情况下,你会有这样的逻辑:

  • Awake
    在测试中,缓存值为
    _actorState
    ,改变里面的参数
    _actorState
  • Awake
    ProtagonistActor
    类中,调用
    InitiateActorState
    方法并创建ActorState类的
    全新实例
    ,默认值为0.
© www.soinside.com 2019 - 2024. All rights reserved.