调试字符串在一个函数中为空,但在另一个函数中填充

时间:2017-09-22 16:31:59

标签: c# unity3d properties

我要么已经开始了很长时间(极有可能),要么特定属性会发生奇怪的事情。当我从我的PlayerController脚本_animalType调试属性Debug.Log("Animal Type is : " + _animalType);时,它将作为空字符串返回,但是当我从CanvasController Debug.Log(player.GetComponent<PlayerController>().AnimalType);调试它时,它显示该字符串填充了正确的数据。谁能看到这里可能发生的事情?谢谢!

'CanvasController.cs'

    public void PrepareAnimalData()
    {
        StartCoroutine(DoPrepareAnimalData());
        Debug.Log("Send To Forest Button Pressed.");
    }

    IEnumerator DoPrepareAnimalData()
    {
        yield return new WaitForEndOfFrame();
        RenderTexture tmp = RenderTexture.active;
        RenderTexture.active = BackLayerController.RenderTexture;

        TmpTexture2D.ReadPixels(new Rect(0, 0, RenderTextureSize.x, RenderTextureSize.y), 0, 0, false);

        player = GameObject.FindGameObjectWithTag("Player");

        PlayerController.animalTex = TmpTexture2D; // set PlayerController animalTex to TmpTexture2D 
        player.GetComponent<PlayerController>().TexToBytes(); // run function from PlayerController
        player.GetComponent<PlayerController>().AnimalType = PageConfig.UniqueId; // set animalType in PlayerController

        Debug.Log(PageConfig.UniqueId);
        Debug.Log(player.GetComponent<PlayerController>().AnimalType);
    }}

PlayerController.cs

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

public class PlayerController : NetworkBehaviour
{
    public static Texture2D animalTex;
    private byte[] textureBytes;

    private string _animalType;
    public string AnimalType
    {
        get
        {
            return _animalType;
        }
        set
        {
            _animalType = value;
        }
    }
    private string _playerID;
    public string PlayerID
    {
        get
        {
            return _playerID;
        }
        set
        {
            _playerID = value;
        }
    }

    private void Awake()
    {
        GameObject gm = GameObject.FindGameObjectWithTag("GameManager");
    }

    void Update()
    {
        if (!isLocalPlayer)
            return;
    }

    public void TexToBytes()
    {
        textureBytes = animalTex.GetRawTextureData();
        DebugAnimalData();
    }

    public void DebugAnimalData()
    {
        Debug.Log("Byte Array Length is : " + textureBytes.Length);
        Debug.Log("Animal Type is : " + _animalType);
        Debug.Log("Player ID is : " + _playerID);
    }
}

2 个答案:

答案 0 :(得分:1)

你打电话给它(显示它输出信息)

player.GetComponent<PlayerController>().TexToBytes();

之前设置

player.GetComponent<PlayerController>().AnimalType = PageConfig.UniqueId; // set animalType in PlayerController

答案 1 :(得分:1)

调用TexToBytes时,它会在内部调用DebugAnimalData日志记录数据。目前,_animalType仍然初始化为null。但是,在此之后,您的下一个语句是通过Setter设置_animalType,因此,下一个Debug日志开始记录值