【问题标题】:How can I fix the errors transform not exist?如何修复错误转换不存在?
【发布时间】:2016-11-01 16:44:28
【问题描述】:
using UnityEngine;
using System.Collections;

public class MakeTwoPoints3D : MonoBehaviour {

    public GameObject cylinderPrefab;

    // Use this for initialization
    void Start () {

        CreateCylinderBetweenPoints(Vector3.zero, new Vector3(10, 10, 10), 0.5f);

    }

    void CreateCylinderBetweenPoints(Vector3 start, Vector3 end, float width)
    {
        var offset = end - start;
        var scale = new Vector3(width, offset.magnitude / 2.0f, width);
        var position = start + (offset / 2.0f);


        Object cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity);
        cylinder.transform.up = offset;
        cylinder.transform.localScale = scale;
    }

    // Update is called once per frame
    void Update () {

    }
}

两行相同的错误:

cylinder.transform.up = offset;
cylinder.transform.localScale = scale;

严重性代码描述项目文件行抑制状态 错误 CS1061“对象”不包含“转换”的定义,并且找不到接受“对象”类型的第一个参数的扩展方法“转换”(您是否缺少 using 指令或程序集引用?) MakeTwoPoints3D.cs 23活跃

【问题讨论】:

  • 你为什么声明为Object
  • 读完here,我看到你是根据变量cylinderPrefab进行实例化的,而 cylinderPrefab 的类型是GameObject,所以把调用改成这个:GameObject cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity) as GameObject;

标签: c# unity3d


【解决方案1】:

ObjectGameObject 的父类,GameObjectTransform 类型的成员。如果您尝试从Object 类的实例访问transform,它将显示以下错误:

Object'不包含'transform'的定义

实例化和使用结果对象作为游戏对象的准确方法正如 Quantic 在comment 中所说:

GameObject cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity) as GameObject;

GameObject cylinder = (GameObject) Instantiate(cylinderPrefab, position, Quaternion.identity);

在使用除 GameObject 以外的其他类型的组件之前,始终使用 null-check 以确保安全。例如:

Rigidbody rb = Instantiate(somePrefab) as Rigidbody;
if(rb != null)
  // use it here

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多