真实被归还为假

时间:2016-12-29 19:35:33

标签: c# unity5

我正在使用Unity并且有一个总是返回false的布尔getter。下面的测试类演示了问题所在。如果我使用接口,构造函数总是返回false,但是当我指定我想要的实现时,我得到正确的结果。我需要使用该接口,因为我有十几个实现,我不知道在运行之前我需要使用哪个。

我整个早上一直在单独执行代码,当它到达第17行时,它会转到正确的实例,m_completed为true,但仍然被赋予false。我希望有人能看出问题是什么原因我现在感到困惑。

编辑:我已经尝试声明继承的类也使用接口(public class CityConstruction : Construction, IConstruction)并且已经解决了问题。我猜我错误地理解了界面是如何工作的,但我不确定为什么会解决这个问题。

测试类:

using UnityEngine;
using System.Collections;

public class TestScript : MonoBehaviour 
{
    public IConstruction my_construction1;
    public CityConstruction my_construction2;

    void Start()
    {
        my_construction = gameObject.GetComponent<CityConstruction>();
    }

    // Update is called once per frame
    void Update () 
    {
        bool construction_completed1 = my_construction1.completed; //Always false
        bool construction_completed2 = my_construction2.completed; //Working
    }
}

构造界面:

using UnityEngine;
using System.Collections;

public interface IConstruction
{
    bool completed { get; }
}

结构:

using UnityEngine;
using System.Collections;
using System;

public class Construction : Structure, IConstruction
{
    private float m_construction;
    private int m_construction_needed;
    private int m_construction_per_second;
    private bool m_completed;               
    public bool completed { get { return m_completed; } }       

    /* UNITY METHODS */
    void Start () 
    {
        m_completed = false;
    }

    void Update () {
        if(m_construction >= m_construction_needed) {
            m_completed = true;
        } else {
            construct();
        }
    }

    private void construct() {
        m_construction = m_construction_per_second * Time.deltaTime;
    }
}

城市建设:

using UnityEngine;
using System.Collections;

public class CityConstruction : Construction
{
    private float m_construction;
    private int m_construction_needed;
    private float m_construction_per_second;
    private bool m_completed;               

    public bool completed { get { return m_completed; } }

    /* UNITY METHODS */
    void Start () 
    {
        m_construction = 0;
        m_construction_needed = 100;
        m_construction_per_second = 100;
        m_completed = false;
    }

    void Update() {
        if (m_construction >= m_construction_needed) {
            m_completed = true;
        } else {
            construct();
        }
    }

    /* PRIVATE METHODS */
    private void construct() {
        m_construction += m_construction_per_second * Time.deltaTime;
    }
}

1 个答案:

答案 0 :(得分:0)

在尝试获取以下行中的已完成值之前,my_construction1是否已实例化:

bool construction_completed1 = my_construction1.completed; //Always false

如果没有,我认为get只是返回属性的默认值,因为它是一个布尔值将是false。