Search code examples
c#unity-game-engine

Unity: How to get the pivot of a game object's sprite?


In unity I'm trying to get the pivot point of the sprite my game object is using.

I changed the sprite's pivot point for it to be easy while I place the game object(Let's call it A) in the game. Now when I try to spawn another object at the transform of A, the new game object , and I know It's hot It's supposed to do, spawns at the top left ofA. I need to somehow calculate the center of the sprite A is using in world coordinates.

I tried this:

Debug.Log(tempGameObj.GetComponent<SpriteRenderer>().sprite.pivot);

But this produces a result as (-80,0,400) while the pivot points are (-0.25, 1.25).

How can I calculate the center?


Solution

  • what you're looking for is the ScreenToWorldPoint method

    Vector3 center = Camera.main.ScreenToWorldPoint(tempGameObj.GetComponent<SpriteRenderer>().sprite.pivot);
    

    Here's the documantation in case you need it https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html