Search Unity

Inicialization object

Discussion in 'Scripting' started by Smixers001, Nov 25, 2015.

  1. Smixers001

    Smixers001

    Joined:
    Oct 28, 2013
    Posts:
    3
    Hi, I found really confusing problem.

    Code (CSharp):
    1.  
    2. [Serializable]
    3. public class AmmoComponent : IComponent {
    4.  
    5.     public override IEnumerator Compute()
    6.     {
    7.         //Code ...
    8.     }
    9.  
    10.     void Start()
    11.     {
    12.         StartCoroutine(GenerateDataLoop());
    13.     }
    14.  
    15.     IEnumerator GenerateDataLoop()
    16.     {
    17.         while (true)
    18.         {
    19.             yield return new WaitForSeconds(0.5f);
    20.             ComponentResult result = new ComponentResult(10);
    21. //PROBLEM------------------------------------------------------------------------
    22.             if (result == null) //Now the result is null. How its possible?
    23.                 Debug.LogError("WTF?");   //
    24. //PROBLEM------------------------------------------------------------------------
    25.  
    26.             yield return new WaitForSeconds(0.1f);
    27.         }
    28.     }
    29. }
    30.  
    Code (CSharp):
    1. public interface IComponentResult {
    2.  
    3.     object Value { get; }
    4.  
    5.  
    6. }
    Code (CSharp):
    1. public class ComponentResult : MonoBehaviour ,IComponentResult {
    2.  
    3.     private object data;
    4.     public ComponentResult(object data)
    5.     {
    6.         this.data = data;
    7.     }
    8.  
    9.     public object Value
    10.     {
    11.         get
    12.         {
    13.             return data;
    14.         }
    15.     }
    16. }
    Code (CSharp):
    1. delegate void ComputingHanler();
    2. public abstract class IComponent : MonoBehaviour {
    3.  
    4.     public bool Computing = false;
    5.     abstract public IEnumerator Compute();
    6.  
    7.     public void StartCompute()
    8.     {
    9.         StartCoroutine(Compute());
    10.     }
    11.  
    12.     public delegate void DataRecive(IComponentResult data);
    13.     public event DataRecive OnComputing;
    14. }
     
    Last edited: Nov 25, 2015
  2. Smixers001

    Smixers001

    Joined:
    Oct 28, 2013
    Posts:
    3
    I found solution.
    Cant instantiate MonoBehavior with "new" i must use Instantiate, or addComponent etc...

    Solution:
    Remove MonoBehavior from ComponentResult, because i dont need MonoBehavior features in this class. Now its works!