简体   繁体   中英

Spawning Bullets

So i am really, really new to Unity and C# and i just want to try a few things like a shooting script. The way i want it to work is that i have a game object, in my case it's called "Glock" and as a child of that game object i have an empty called "bulletSpawn". I now want to assign a script to "bulletSpawn" that spawns in an predefined object whenever i hit the left mouse button.

What i tried:

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

public class spawnBullet : MonoBehaviour
{

    public GameObject bullet;
    // Start is called before the first frame update
    void Start()
    {
    
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            GameObject newBullet = Instantiate(bullet, new Vector3(0, 0, 0), Quaternion.identity);
        
        }
    }
}

And it kinda works. Whatever, it clones everything in an exponential way, so when i hit the left mouse button it spawns in the object but it also spawns in an object called "Glock(Clone)" and if i hit it again, it spawns: "Glock(Clone)","Glock(Clone)(Clone)","bullet(Clone)" and "bullet(Clone)(Clone)". And that doubles each time i click. My second problem is, that it spawns every object at the global coordinates [0,0,0] and not the local ones of the empty.

As Helmi say are you using a bullet prefab and not the Glock prefab? This code under should fix your position problem.

if (Input.GetButtonDown("Fire1"))
{
    GameObject newBullet = Instantiate(bullet, transform.position, Quaternion.identity);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM