我正在从在线教程中编程JRPG,以尝试学习Unity和C#代码。这是一个用于创建要攻击的敌方单位菜单的程序:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using UnityEngine.Experimental.UIElements;
public class CreateEnemyMenuItem : MonoBehaviour {
[SerializeField]
private GameObject targetEnemyUnitPrefab;
[SerializeField]
private Sprite menuItemSprite;
[SerializeField]
private Vector2 initialPosition, itemDimensions;
[SerializeField]
private KillEnemy killEnemyScript;
private void Awake()
{
GameObject enemyUnitsMenu = GameObject.Find("EnemyUnitsMenu");
GameObject[] existingItems = GameObject.FindGameObjectsWithTag("TargetEnemyUnit");
Vector2 nextPosition = new Vector2(this.initialPosition.x + (existingItems.Length * this.itemDimensions.x), this.initialPosition.y);
GameObject targetEnemyUnit = Instantiate(this.targetEnemyUnitPrefab, enemyUnitsMenu.transform) as GameObject;
targetEnemyUnit.name = "Target" + this.gameObject.name;
targetEnemyUnit.transform.localPosition = nextPosition;
targetEnemyUnit.transform.localScale = new Vector2(0.7f, 0.7f);
targetEnemyUnit.GetComponent<Button>().onClick.AddListener (() => selectEnemyTarget());
targetEnemyUnit.GetComponent<Image>().sprite = this.menuItemSprite;
killEnemyScript.menuItem = targetEnemyUnit;
}
public void selectEnemyTarget()
{
}
}
在游戏测试期间,在第29行(实例化targetEnemyUnit
处,我收到NullReferenceException错误,我认为这意味着实例化无法正常工作(在此处也突出显示,但在Visual Studio中不突出显示)。我主要是从教程中学习,但这很匹配,而且我不确定在这里我到底在做什么错。
在检查器中未设置targetEnemyUnitPrefab,在这种情况下,您只需要单击包含该脚本的GameObject,在检查器中将您的预制件拖放到'targetEnemyUnitPrefab'或未正确标记敌人单元菜单,在这种情况下,请单击在应该被标记的'GameObject'上,并确保在检查器的右上角将其标记为'EnemyUnitsMenu'
请注意,当您创建一个新标签并选择了一个游戏对象时,该对象不会应用该标签,您必须回到游戏对象并从下拉菜单的底部选择它。
GameObject targetEnemyUnit = Instantiate(this.targetEnemyUnitPrefab, enemyUnitsMenu.transform) as GameObject;
好吧,您有一个私有对象作为预制件->私人GameObject targetEnemyUnitPrefab