Unity开发中CS0138及Transform相关代码错误求助
解决Unity C#脚本中的编译错误
初始错误
Assets\Scripts\enemy.cs(4,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'Transform' is a type not a namespace. Consider a 'using static' directive instead
删除using UnityEngine.Transform;后出现的错误:
- .cs(18,18): error CS0029: Cannot implicitly convert type 'UnityEngine.Transform' to 'UnityEngine.Transform[]'
- .cs(24,28): error CS1061: 'Transform[]' does not contain a definition for 'position' and no accessible extension method 'position' accepting a first argument of type 'Transform[]' could be found
- .cs(24,39): error CS0120: An object reference is required for the non-static field, method, or property 'Transform.position'
- .cs(25,9): error CS0120: An object reference is required for the non-static field, method, or property 'Transform.Translate(Vector3, Space)'
- .cs(27,29): error CS0120: An object reference is required for the non-static field, method, or property 'Transform.position'
- .cs(27,56): error CS1061: 'Transform[]' does not contain a definition for 'position' and no accessible extension method 'position' accepting a first argument of type 'Transform[]' could be found
- .cs(30,22): error CS0029: Cannot implicitly convert type 'UnityEngine.Transform' to 'UnityEngine.Transform[]'
修复后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class enemy : MonoBehaviour { public float speed; public Transform[] waypoints; public Transform target; // 修正:从数组改为单个Transform对象 private int destPoint = 0; void Start() { target = waypoints[0]; } void Update() { // 修正:使用当前对象的transform实例,而非类名调用 Vector3 dir = target.position - transform.position; transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World); // 修正:使用当前对象的transform实例 if (Vector3.Distance(transform.position, target.position) < 0.3f) { destPoint = (destPoint + 1) % waypoints.Length; target = waypoints[destPoint]; } } }
错误原因及修复说明
- CS0138错误:
Transform是UnityEngine命名空间下的类,不是独立命名空间,无需添加using UnityEngine.Transform;,已有using UnityEngine;即可直接使用Transform类型,删除该行即可。 - CS0029错误:
target被声明为数组类型,但实际需要的是单个目标Transform对象,将public Transform [] target;改为public Transform target;即可解决类型不匹配问题。 - CS0120错误:
Transform.position和Transform.Translate是实例成员,必须通过对象实例调用。在MonoBehaviour脚本中,直接用小写的transform就能访问当前挂载对象的Transform组件,不能通过类名Transform调用。 - CS1061错误:原本
target是数组,数组没有position属性,改为单个Transform类型后,即可正常访问该属性。
内容的提问来源于stack exchange,提问作者Sosso
相关产品推荐
相关产品推荐

