Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want an Object to spawn in a specific area in my game after i press the button

my game Item is spawnning behind the spawn button in game i don’t know what to do to spawn it in the midddle of the screen:

Potion screen

I made a button just for testing purposes to spawn the potion and here is the code i assigned to it to spawn my item:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

public class HerbSpawner : MonoBehaviour
{
    //Here, we declare variables.
    public GameObject objToSpawn;
    public Transform groupTransform;


    //public means the var is exposed in the inspector, which is super helpful.


    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {


        //let's also spawn on button press:
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));

            if (hit.collider && hit.collider.CompareTag("Bush"))
            {
                SpawnIt();
            }
        }

        void SpawnIt()
    {
        //spawn our coin:
        Instantiate(objToSpawn, transform.position, Quaternion.identity, groupTransform);
    }
}
    }

>Solution :

As you want to instantiate it in the middle of the screen,

void SpawnIt()
{
    Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
    Instantiate(objToSpawn, spawnPos, Quaternion.identity, groupTransform);
}

Sidenote:

If you are repeatedly spawning in the middle of the screen, cache the spawn position

Vector2 spawnPos;

void Start()
{
    spawnPos = Camera.main.ViewportToWorldPoint(new Vector2(0.5f, 0.5f));
}

void SpawnIt()
{
    Instantiate(objToSpawn, spawnPos, Quaternion.identity, groupTransform);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading