This is about to drive me insane. My goal is to draw a 2D rectangle with the same dimensions as the hitbox I want to create in Unity. Because my Box Collider 2D isn’t visible, I’m trying to make a visual aid to see where it actually is in the world.
Unfortunately, drawing this rectangle has been a far bigger headache than I would have hoped. I’ve searched for many examples as to how to do this - I’ve looked at GL.DrawTexture and GL.Box, but this will not work because drawing this rectangle is an Animation Event. In short, I am calling a function during a particular frame that is dynamically creating a hitbox, and then I am trying to get rid of it a few frames later. The rectangle I am drawing is only relevant for these frames, and I’m not doing anything in OnGUI.
Right now, I have:
Texture2D tex = new Texture2D (1, 1);
tex.SetPixel (0, 0, Color.black);
tex.Apply ();
Rect pos = new Rect (transform.position.x, transform.position.y, 10, 10);
Sprite newSprite = Sprite.Create (tex, pos, new Vector2 (0.5f, 0.5f), 128);
GameObject obj = new GameObject ();
obj.name = "Hitbox";
obj.AddComponent<SpriteRenderer> ();
SpriteRenderer spr = obj.GetComponent<SpriteRenderer> ();
spr.sprite = newSprite;
I am trying to draw a little black box in front of the player during a walk animation. Not only does this not work, I can’t get rid of the rectangle when I need to. The rectangle doesn’t even appear where it should - it’s always at 0,0.
Any help would be appreciated; this problem is making me lose my mind.