【问题标题】:Set Position of a Sprite in Unity在 Unity 中设置 Sprite 的位置
【发布时间】:2019-08-07 03:14:23
【问题描述】:

我想通过脚本设置精灵的位置,但我不能使用

gameObj.transform.localPosition = new Vector3(0,0,0);

不知何故。

它给了我错误“Sprite 不包含转换的定义,并且找不到接受 Sprie 类型的第一个参数的可访问扩展方法转换...”

【问题讨论】:

  • 请添加完整的代码示例。您提供的 sn-p 太少,无法给出答案。 Unity 中使用了各种类型的“Sprite”。您是指SpriteRenderer 还是具有Image.sprite 类型Sprite 的属性的Image
  • Gameobject 可以添加一些 Compoent ,比如 Image ,Image 需要 sprite 来显示,所以你只需移动 gameobject 就好了。 Sprite 是资源而不是“游戏对象”,您不能移动资源吗?

标签: c# unity3d transform sprite


【解决方案1】:

如果你想处理游戏对象,你的gameObj 似乎是一个sprite而不是GameObject

您可以在Inspector

中使用公共变量来分配精灵的游戏对象
public GameObject gameObj;  

你设置位置的方法现在有效。

gameObj.transform.localPosition = new Vector3(0,0,0);

如果要访问精灵的属性,可以使用GetComponent

Debug.Log(gameObj.GetComponent<Sprite>().pivot); 

也许你也应该检查一下SpriteRenderer

【讨论】:

    【解决方案2】:

    设置游戏对象的位置与设置精灵位置相同。
    (包括精灵是游戏对象的一个​​组件)

    // Moves the entire gameobject. (Aka moving the 'sprite' in the gameobject along with it)    
    gameObject.transform.localPosition = new Vector3(0,0,0);
    

    您的错误发生是因为gameObjSprite 类型,而Sprite 没有转换。拥有它的游戏对象。

    编辑

    如果您只想移动游戏对象的“精灵”,请创建一个托管精灵渲染器的子游戏对象,然后自行移动子对象,如下所示:

    ObjectWithSprite 的检查员应该类似于:

    当然,将MovingGameObject 脚本替换为您想要控制游戏对象精灵移动的脚本:

    public class MovingGameObject : MonoBehaviour {
        void Update() {
            // Or some other location;
            gameObject.transform.position = Vector3.zero;
        }
    }
    

    【讨论】:

    • 我该怎么做?我对统一很陌生^^我非常感谢!
    • @KamilJu 编辑了我的答案,它应该告诉你如何做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多