所以我已经有了一个非常基本的战斗脚本,它将玩家和脚本所附加的任何敌人纳入检查器中。但是,当我点击“播放”来测试游戏时,我添加到检查器中的玩家变量的值消失了,就好像我从未添加任何内容一样。当我停止时它再次出现。
我的 super 简单的战斗脚本
using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.UI;
public class BasicCombat : MonoBehaviour
{
public KennedyClass playerK;
public pawnClass pawn;
public archerClass archer;
// Use this for initialization
void Start()
{
playerK = GetComponent<KennedyClass>();
pawn = GetComponent<pawnClass>();
archer = GetComponent<archerClass>();
playerK.charHP = playerK.maxHP;
}
// Update is called once per frame
void Update()
{
}
public void Attack()
{
if (gameObject.CompareTag("Pawn"))
{
while (playerK.charHP != 0 & pawn.pawnHP !=0)
{
playerK.charHP -= pawn.pawnDamage;
playerK.HPCount();
Debug.Log("Player - " + playerK.charHP);
var option = EditorUtility.DisplayDialogComplex(
"Attack",
"Do you want to attack?",
"Yes",
"No",
"Exit");
switch (option)
{
case 0:
pawn.pawnHP -= playerK.atkP;
Debug.Log("Pawn - " + pawn.pawnHP);
break;
case 1:
//Exit loop (for now)
break;
case 2:
//Exit loop (for now)
break;
}
}
}
else if (gameObject.CompareTag("Archer"))
{
while (playerK.HP != 0 & pawn.pawnHP != 0)
{
playerK.HP -= archer.archerDamage;
Debug.Log("Player - " + playerK.HP);
var option = EditorUtility.DisplayDialogComplex(
"Attack",
"Do you want to attack?",
"Yes",
"No",
"Exit");
switch (option)
{
case 0:
archer.archerHP -= playerK.atkP;
Debug.Log("Archer - " + archer.archerHP);
break;
case 1:
//Exit loop (for now)
break;
case 2:
//Exit loop (for now)
break;
}
}
}
if (playerK.charHP == 0)
{
Debug.Log("Player death");
Application.LoadLevel(0);
}
if (pawn.pawnHP == 0)
{
Debug.Log("Enemy death");
pawn.GetComponent<Renderer>().enabled = false;
}
if (archer.archerHP == 0)
{
Debug.Log("Enemy death");
archer.GetComponent<Renderer>().enabled = false;
}
}
}
最佳答案
您正在更改 Start
中的变量功能。删除该行
playerK = GetComponent<KennedyClass>();
来自您的Start
函数将变量保留在检查器中设置的状态。
为了解释一下发生了什么,当您在检查器中分配玩家变量时,您将给它一个对 GameObject
的引用。与 KenedyClass
附有脚本。这是我假设您想要的引用。
但是,当您调用playerK = GetComponent<KennedyClass>();
时然后你会说'忘记我在检查器中设置的内容,寻找 KennedyClass
这个脚本附加到的游戏对象上的组件并设置 playerK
等于它'。如果没有KennedyClass
脚本附加到这个游戏对象,我假设没有,那么它将返回 null
并删除检查器中的设置。
关于c# - Unity Inspector 在运行时清除变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125759/