当我实例化一个对象并设置变量时,它在unity c#中不起作用
本文关键字:它在 unity 不起作用 变量 实例化 一个对象 设置 | 更新日期: 2023-09-27 18:05:41
我正在尝试实例化一个对象,当实例化时,在脚本spawnPlayer
中实例化一个变量uiManager
的对象中设置一个变量uiManager
。
当我播放并暂停游戏时,然后查看实例化的对象,变量未设置。
这是代码!
using UnityEngine;
using System.Collections;
public class playerSpawner : MonoBehaviour {
public GameObject[] cars;
public uiManager ui;
int carSpawned;
void Start ()
{
spawn ();
}
void spawn ()
{
Instantiate (cars [carPicController.next], transform.position, transform.rotation);
carPicController.next = carSpawned;
Debug.Log ("player spawned");
setuiManager ();
}
void setuiManager ()
{
//get the thing component on your instantiated object
uiManager ui = cars [carSpawned].GetComponent<uiManager>();
//set a member variable (must be PUBLIC)
ui = ui;
}
}
问题在于范围。
void setuiManager ()
{
//get the thing component on your instantiated object
uiManager ui = cars [carSpawned].GetComponent<uiManager>();
//set a member variable (must be PUBLIC)
this.ui = ui;
}
问题是您创建了一个与类成员同名的临时变量。在setuiManager
内部,它将假定ui
引用的是临时变量,而不是数据成员。