从脚本引用的布尔没有更新?

时间:2020-01-14 22:50:20

标签: c# unity3d

我在名为Something的脚本中有一个名为isDead的布尔值,可以在检查器中进行更改。我使用Get Component在另一个名为main的脚本中引用bool,在其中我将其称为isD,并使用Debug.Log在控制台中查看它。当我启动scrpit时,控制台显示的是bool的正确状态,但是当我在检查器中更改其值时,控制台中的值保持不变。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour
{
    bool isD;
    public GameObject Side;
    void Start()
    {
        isD = Something.GetComponent<Something>().isDead;
        Debug.Log(isD);
    }

    // Update is called once per frame
    void Update()
    {
       Debug.Log(isD);
    }
} 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Something : MonoBehaviour
{
    public bool isDead;
    void Start()
    {
        isDead = false;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

2 个答案:

答案 0 :(得分:1)

bool是一个值类型,因此在分配它时,您是在复制值,而不是引用。相反,您可以只保留对象的引用,并根据需要从该对象获取isDead值。

请注意,默认情况下无法保证Start调用的顺序,因此您应该考虑将需要首先运行的代码放在Awake中。

此外,空魔术方法会浪费处理时间。摆脱任何更新定义,而不是将其保留为空。

将您的Something类重命名为Side(肯定是某种错字),它看起来像这样:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour
{
    Side sideOfSomething;
    public GameObject Something;
    void Start()
    {
        sideOfSomething = Something.GetComponent<Side>();
        Debug.Log(sideOfSomething.isDead);
    }

    // Update is called once per frame
    void Update()
    {
       Debug.Log(sideOfSomething.isDead);
    }
} 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Side : MonoBehaviour
{
    public bool isDead;
    void Awake() // called prior to any Start
    {
        isDead = false;
    }

    // Empty magic methods waste cycles
}

答案 1 :(得分:-1)

您必须在更新中而不是在开始时更改bool 那么您可以看到isD值发生了变化

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour
{
    bool isD;
    public Something something;
    void Start()
    {

     something = GetComponent<Something>();
    }

    // Update is called once per frame
    void Update()
    {
       isD = something.isdead;
       Debug.Log(isD);
    }
} 
相关问题