Unity C#:特定Torso显示时生成对象异常的修复方案
问题修复方案
教程使用的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Trial_Changer : MonoBehaviour { [Header("Sprite To Change")] public SpriteRenderer bodyPart; [Header("Sprites to Cycle Through")] public List<Sprite> options = new List<Sprite>(); public static int currentTorsoOption = 0; public void NextOption () { currentTorsoOption++; if (currentTorsoOption >= options.Count) { currentTorsoOption = 0; } bodyPart.sprite = options[currentTorsoOption]; } public void PreviousOption() { currentTorsoOption--; if (currentTorsoOption <= 0) { currentTorsoOption = options.Count - 1; } bodyPart.sprite = options[currentTorsoOption]; } }
尝试实现“Torso 2显示时生成对象”的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpeechAppears : MonoBehaviour { public GameObject speechBubbleTOSpawn; private int Torso = Trial_Changer.currentTorsoOption; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Torso == 2) { Instantiate(speechBubbleTOSpawn); } } }
问题描述
当前对象始终显示,无法实现仅当Torso 2在屏幕上显示时才生成对象的需求,请问该如何修复?
错误原因及修复方法
错误原因
- 静态变量未实时读取:你这里把
Trial_Changer.currentTorsoOption的值存在了private int Torso里,但这个赋值只在脚本初始化时执行一次,后续currentTorsoOption变化时,Torso不会同步更新,导致判断逻辑完全失效。 - 重复生成对象:就算判断逻辑正确,
Update方法每帧都会执行,会无限生成气泡对象,既浪费资源又导致显示异常。
修复后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpeechAppears : MonoBehaviour { public GameObject speechBubbleToSpawn; private GameObject spawnedBubble; // 记录已生成的气泡对象,避免重复创建 void Update() { // 实时读取当前的Torso选项,不要缓存成固定变量 int currentTorso = Trial_Changer.currentTorsoOption; if (currentTorso == 2) { // 只有当气泡还没生成的时候才创建 if (spawnedBubble == null) { spawnedBubble = Instantiate(speechBubbleToSpawn, transform.position, Quaternion.identity); // 可选:把气泡设为当前物体的子对象,方便位置管理和销毁 spawnedBubble.transform.SetParent(transform); } } else { // 切换到其他Torso时,销毁已生成的气泡 if (spawnedBubble != null) { Destroy(spawnedBubble); spawnedBubble = null; } } } }
额外优化建议
- 用事件替代每帧判断:可以在
Trial_Changer里添加一个OnTorsoChanged事件,切换Torso时触发这个事件,SpeechAppears监听事件来处理生成/销毁逻辑,比每帧轮询更高效。 - 调整气泡生成位置:根据实际需求设置
Instantiate的位置参数,避免气泡和Torso重叠。
内容的提问来源于stack exchange,提问作者TirimasuBread
相关产品推荐
相关产品推荐

