2016-12-29 118 views
-6

我使用的统一,并有一个布尔吸气,就是始终返回false。下面的测试类展示了问题所在。如果我使用接口构造函数总是返回false,但是当我指定我想要的实现时,我会得到正确的结果。我需要使用接口,因为我有十几个实现,我不知道在运行时需要使用哪一个。真正返回假

我已经通过代码整个上午不断加强,当它涉及到17行它转到正确的实例,这m_completed为真,但还是被分配假的。我希望有人能够看到现在我感到困惑的是什么问题。

编辑:我试过,宣布继承的类也使用接口(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; 
    } 
} 
+3

你设置在吸气本身断点?这很可能是你确实有Construction' – BradleyDotNET

+0

您的建筑类不是compilebar的'两个实例,你已经忘记了指定完整的物业 –

+0

的类型,请提供重现问题 – Breeze

回答

0

是my_construction1被instaniated您尝试获得的以下行结束前值:

bool construction_completed1 = my_construction1.completed; //Always false 

如果没有,我会觉得得到的是刚刚返回属性的默认值,因为它是其中一个布尔值将是假的。

相关问题