Joshua Merrett
Joshua Merrett

Reputation: 13

Unity GameObjects are not rendering after Instantiation

I am making a simple game for one of my college modules. When I click with the left mouse button I need a boxing glove to appear.

The problem I am having, is that the gloves are not rendering, the appear in the hierarchy but do not show on the screen, see images

Image 1:

enter image description here

Image 2:

enter image description here

My code is as follows:

public class script_CreateBoxingGlove : MonoBehaviour {
    public GameObject BoxingGlove;

    void Start () {

    }   

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            var position = Input.mousePosition;
            Instantiate (BoxingGlove, position, Quaternion.identity);
        }
    }
}

Any help would be greatly appreciated :)

Upvotes: 1

Views: 181

Answers (1)

DRKblade
DRKblade

Reputation: 347

Input.mousePosition is the position on the screen of the mouse, not in world coordinates (it is documented here).

So you have to convert it to world coordinates before using it as the position. The instantiate statement should be something like this

Vector2 position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Instantiate (BoxingGlove, position, Quaternion.identity);

This uses the camera in the hierarchy that is tagged as "MainCamera" to convert. So to make this code work, you will have to make sure there is a camera tagged like that in your hierarchy.

Upvotes: 1

Related Questions