简体   繁体   English

在Unity中设置Sprite的位置

[英]Set Position of a Sprite in Unity

I want to set the position of a Sprite via Script but i cant use 我想通过脚本设置Sprite的位置,但是我不能使用

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

somehow. 不知何故。

it gives me the error "Sprite does not contain a definition for transform and no accesible extension method transform accepting a first argument of type Sprie could be found..." 它给我一个错误“ Sprite不包含转换的定义,并且找不到可以接受的扩展方法转换,该转换接受类型为Sprie的第一个参数...”

Setting a game object's position is the same as setting the sprite positions. 设置游戏对象的位置与设置精灵位置相同。
(Included the fact that the sprite is a component of the game object) (包括精灵是游戏对象的组成部分的事实)

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

Your error occured due to the fact that gameObj is a type Sprite , and Sprite don't have transforms. 由于gameObjSprite类型,而Sprite没有转换, gameObj发生了您的错误。 Its game objects that have it. 它拥有它的游戏对象。

Edit 编辑

If you wanted to move the 'sprite' of a game-object only, make a child gameobject that hosts the sprite-renderer instead, and move the child by itself, like so: 如果您只想移动游戏对象的“精灵”,则制作一个子代游戏对象来承载精灵渲染器,然后单独移动子代,如下所示:

游戏对象的图像

And your inspector for ObjectWithSprite should look similar to: 您的ObjectWithSprite的检查ObjectWithSprite应类似于: ObjectWithSprite的检查器图像

Of course, replacing MovingGameObject script with your intended script that will control the movement of the sprite of the gameobject: 当然,用您想要的脚本替换MovingGameObject脚本,该脚本将控制游戏对象精灵的移动:

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

It seems your gameObj is a sprite not GameObject , if you want to handle the gameObject 看来你gameObj是一个精灵不是游戏物体 ,如果你要处理的游戏对象

You can use public variable to assign the gameObject of sprite in Inspector 您可以使用公共变量在Inspector中分配sprite的gameObject

public GameObject gameObj;  

and your method to set position works now. 并且您的位置设置方法现在可以正常工作。

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

if you want to access the properties of sprite, you can use GetComponent 如果要访问Sprite的属性,可以使用GetComponent

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

Maybe you should also check SpriteRenderer 也许您还应该检查SpriteRenderer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM