Unity中C#脚本报CS0106错误:private修饰符对该项无效如何解决
CS0106错误解决说明
错误根源
你遇到的CS0106: The modifier 'private' is not valid for this item错误核心原因是方法嵌套定义:你把spawnEnemy()、asteroidWave()两个方法写在了Start()方法的内部,C#语法不允许在成员方法内部再定义带访问修饰符的类成员方法,因此private修饰符会被判定为无效。
同时你的代码还存在几个伴随问题会引发后续报错:
- 未声明
screenBounds变量,直接调用会提示变量不存在 screenBounds初始化逻辑错误,未赋值就调用自身的x/y属性- 协程调用方法拼写错误:
StartCorountine应为StartCoroutine - 协程方法名拼写不一致:调用时写的
asteroidWave(),实际定义的方法名少了字母e,为astroidWave() Start()方法的闭合大括号位置错误,把两个业务方法包裹在了Start的作用域内
修复后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class deployAsteroids : MonoBehaviour { public GameObject asteroidPrefab; public float respawnTime = 1.0f; // 补充声明screenBounds变量 private Vector2 screenBounds; void Start() { screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z)); // 修正协程调用拼写错误 StartCoroutine(asteroidWave()); } // 方法移到Start外部,作为类成员 private void spawnEnemy() { GameObject a = Instantiate(asteroidPrefab) as GameObject; a.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), screenBounds.y * -2); } // 修正方法名拼写,和调用处保持一致 IEnumerator asteroidWave() { while (true) { yield return new WaitForSeconds(respawnTime); spawnEnemy(); } } }
关键修改点说明
- 调整大括号位置,将
spawnEnemy()、asteroidWave()移到Start()方法外部,成为类的同级成员方法 - 补充
Vector2类型的screenBounds私有成员变量声明 - 修正
screenBounds初始化逻辑,使用Screen.width、Screen.height获取屏幕尺寸,避免未赋值就调用自身属性的问题 - 修正
StartCoroutine方法的拼写错误 - 统一协程方法名拼写为
asteroidWave(),和调用处保持一致
内容的提问来源于stack exchange,提问作者EverettRike
相关产品推荐
相关产品推荐

