Problem with creating object on touch

Hello guys please i just want ur advice how to fix this: i want to create object (in prefab) on the place where i touch the screen but it instantly sending my this error: Object reference not set to an instance of an object

public GameObject obj1; // obj1 is prefab he has(rigidbody2d,sprite renderer,box collider2d)

void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 TouchPosition = Camera.main.ScreenToViewportPoint(touch.position);

if(touch.phase == TouchPhase.Began)
Instantiate(obj1, TouchPosition, Quaternion.identity);
}
}

and in hiearchy i have GameObject only with this script

Populate the obj1 variable in the inspector with your prefab.

ik. it still sending same error

How to report problems productively in the Unity3D forums:

http://plbm.com/?p=220

Help us to help you.

Also, please use code tags: https://discussions.unity.com/t/481379

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreatingOBJ : MonoBehaviour
{
    public GameObject obj1;
    void Update()
    {
        if (Input.touchCount > 0)
        {
           Touch touch = Input.GetTouch(0);
            Vector3 TouchPosition = Camera.main.ScreenToViewportPoint(touch.position);

            if (touch.phase == TouchPhase.Began)
                Instantiate(obj1, TouchPosition, Quaternion.identity);
        }
    }
}

ok ?

Looks great. I don’t see any error. You do. What is that error? What do you see in code on that line? What does Google tell you about that error?

Also, read the documentation here:

And reason about what you want the .z value to be for the Vector3 that you pass in.

You’ll find that value is quite important to your outcome.

Let me quote this line from the docs:

i changed Camera.ScreenToViewportPoint to ScreenToWorldPoint and then i checked Hierarchy and Inspector for errors
but still no object is created after i click on the screen
and it still sending the same error(Object reference not set to an instance of an object) when i click on error message it points (in VisualStudio) to this line of code:
Vector3 TouchPosition = Camera.main.ScreenToWorldPoint(touch.position);

so i tried paste TouchPosition = GetComponent(); into void Start() but it still does not work
no matter if i change Vector3 on Vector2

at this point i really don’t know why objects does not spawn :eyes:

It’s likely your scene camera is not tagged with MainCamera as Camera.main simply does FindObjectWithTag(“MainCamera”);

Thank you so much and u2 Kurt-Dekker ! it works now, next time I will be more attentive…