如何更改另一个类中的变量?
public class Manager : MonoBehaviour {
public bool isDead = false;
void Start () {
GameObject Slugbert = (GameObject)Instantiate(Resources.Load("Slugbert"));
}
void Update () {
}
}
我正在尝试将isDead布尔值从false更改为true。
using UnityEngine;
using System.Collections;
using System;
public class Health : MonoBehaviour {
public GameObject obj;
Manager manager;
public int maxHealth = 10;
public int health = 10;
public GameObject deathInstance = null;
public Vector2 deathInstanceOffset = new Vector2(0,0);
void Start () {
manager = obj.GetComponent<Manager>();
health = maxHealth;
}
void Update () {
if (Input.GetKey ("up")) {
Debug.Log ("Self Destruct Activated");
TakeDamage();
}
}
public void TakeDamage()
{
health -= 100;
if (health <= 0)
{
OnKill();
Debug.Log ("Running it");
}
}
public void OnKill()
{
manager.isDead = true;
Debug.Log(manager.isDead);
if (deathInstance) {
var pos = gameObject.transform.position;
GameObject deathObject = Instantiate (deathInstance, new Vector3(pos.x + deathInstanceOffset.x, pos.y + deathInstanceOffset.y, pos.z), Quaternion.identity) as GameObject;
}
Destroy(gameObject);
}
}
我在debug.log中添加了显示manager.isDead的值,并且它打印为true,但是在检查器中运行它并单击GameControl时,包含Manager.cs的对象显示isDead = false 。我不确定如何在GameControl Manager.cs中获得isDead的值等于true。
谢谢,我是Unity的新手
答案 0 :(得分:0)
在Health类中尚未设置manager属性。
将Manager manager;
更改为Manager manager = new Manager();
您没有从另一个类更改变量,但您正在更改某个类的对象的属性。
答案 1 :(得分:0)
您的描述不清楚。所以这里有两种可能的变体:
1。场景中有两个对象,第一个附加了Manager.cs,第二个附加了Health.cs。
在这种情况下的解决方案:
Health.cs中的 a。修改Manager经理; - &GT; 公开经理经理; (在这种情况下,当您选择第二个物体时,您将能够在检查员中找到一个字段
b。选择场景中的第二个对象,锁定(按小锁图标)检查员
c。选择第一个对象,然后将其拖放到第二个对象的“管理员”字段中。
2。你有一个对象,并附有两个脚本。
解决方案:
添加到Health.cs中的启动功能
void Start () {
health = maxHealth;
manager = gameObject.GetComponent<Manager>();
}
答案 2 :(得分:0)
你遇到这个错误的原因是因为团结不知道这个Manager
是什么
在统一中,脚本无法自动识别其他脚本,即使它位于同一文件夹或游戏对象中
要访问其他脚本,您需要为变量manager
分配实际脚本manager.cs
。方法如下:
Health.cs
// This is the game object where manager.cs is attached to.
// Assign the game object from the inspector, drag drop the game object to this field.
// If manager.cs and health.cs is in the same game object, you don't need this.
public GameObject obj;
Manager manager;
void Start () {
health = maxHealth;
// This is where you actually assign manager variable
// GetComponent<Manager> meaning you want to get a game object component with
// type Manager, which is your script manager.cs
// If manager.cs and health.cs is in the same game object, replace "obj" with
// "gameObject"
manager = obj.GetComponent<Manager>();
}
然后你应该能够像你想要的那样改变变量。希望这会有所帮助。
答案 3 :(得分:0)
尝试改变
public bool isDead = false;
到
public static bool isDead = false;
在Manager类中并相应地更改