How can i clone an object one by one in unity - c#

So basically i wanted to learn about instantiate and I have tried this code below:
public Transform spawnpos;// the position where i wanted to clone my sphere
void Update()
{
if (Input.GetKeyDown("q"))
{
Instantiate(gameObject, spawnpos.position, spawnpos.rotation);
Destroy(gameObject, 2);
}
}
the thing is, when i press "q" it does spawn a sphere and gone in about 2 secs, but if i continously press "q" the amount of clones spawned are getting bigger as i press and it wont be destroyed after 2 seconds.
In Conclusion, how can i spawn a sphere when i pressed "q", and it will spawn 10 if i pressed "q" 10 times
tysm for reading this far! have a nice day! :)

First thing's first, you can't instantiate the gameobject to which this script is attached through this script because:
If you instantiate a gameobject, there will be two gameobjects in the scene and both will be having this script. Hence if you press Q again, two gameobjects are instantiated.
Solution:
Create an empty gameobject in the scene and create a new script ObjectSpawner.cs and attach it to this empty gameobject.
public class ObjectSpawner : MonoBehaviour {
public Transform spawnpos;// the position where I wanted to clone my sphere
public GameObject sphere;// gameobject you want to spawn
void Update() {
if (Input.GetKeyDown("q")) {
GameObject obj = Instantiate(sphere, spawnpos.position, spawnpos.rotation);
Destroy(obj, 2);
}
}
}
In the above script as you can see there's a field for the sphere gameobject. Drag it to the slot in the inspector.

Related

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);
}

How to spawn objects in Unity?

I am trying to build a flappy bird like game and I am trying to spawn enemy birds and gold coins so I have written the C# code and the made the prefabs, but when I run the bird and the coins are not respawning.
This is the respawn code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnPlayer : MonoBehaviour
{
public GameObject GameObjectToSpawn;
private GameObject Clone;
public float timeToSpawn = 4f;
public float FirstSpawn = 10f;
// Update is called once per frame
void Update()
{
FirstSpawn -= Time.deltaTime;
if (FirstSpawn <= 0f)
{
Clone = Instantiate(GameObjectToSpawn, gameObject.transform.localPosition, Quaternion.identity) as GameObject;
FirstSpawn = timeToSpawn;
}
}
}
screenshot of unity:
This where i am respawning the first enemy bird:
From your second screenshot it seems to be spawned but way off the screen! You can still see the tiny little island in the bottom left corner.
You thought seems to be that you have to spawn it in the Canvas pixel space using the spawn point's localPosition. But this is not the case since Instantiate places it into the scene root (without any parent) with absolute world-space position into the scene.
You should rather actually place the spawn point to the absolute world position where the spawn should happen and rather use
Clone = Instantiate(GameObjectToSpawn, transform.position, Quaternion.identity);
Btw no need for the as GameObject since Instantiate already returns the type of the given prefab.

Score increasing by 2 when it should be increased by 1

I have a bullet and when it hits a target it should increment the score by 1. but the score is increasing by 2. the bullet is a capsule with a collider and rigibody and the target is a cylinder with a collider and rigibody
the code on the bullet
public class Bullet : MonoBehaviour {
float lifespan = 2;
void Start()
{
// destroy the bullet
Destroy(gameObject, lifespan);
}
void OnTriggerEnter(Collider other) //collider event
{
if (other.gameObject.CompareTag("Score"))
{
Score.score = Score.score + 1;
}
}
}
the score code
public class Score : MonoBehaviour {
public static int score; // The player's score.
Text text; // Reference to the Text component.
void Start()
{
// Set up the reference.
text = GetComponent<Text>();
// Reset the score.
score = 0;
}
void Update()
{
// Set the displayed text to the score value.
text.text = "Score: " + score;
}
}
I've solved this exact problem before but I searched for it to mark this as a duplicate but couldn't find it. It's probably deleted by the OP.
There are 2 possible reasons why your score could update multiple times.
1.Your script (Bullet) is attached to your GameObject multiple times. This is very likely the problem. It is very likely that it is attached to random empty GameObject.
Fix:
A.Check that gameObject.AddComponent<Bullet>(); is not anywhere in any script in your project. The AddComponent will add new Bullet to your GameObject.
B.Search for duplicated script on GameObjects through the Editor.
Select your Bullet script, go to Assets --> Find References in Scene. It will show you every GameObject that has this script attached to it. Remove it from all of them except for your bullet GameObject.
2.You have more than one collider on the GameObject. Maybe a collider as a child. You must find a way to handle that. If this is the case, you can ignore the child colliders by putting them in a separate tag and checking it.
You are already checking the tags which is fine. Just change the tag of the child colliders to something else that is not "Score" so that other.gameObject.CompareTag("Score") will not be true.

Instantiate gameobjects as child of main object

is it a way for instantiate gameobjects as child of main? This is my example of code
void MakeCubes ()
{
GameObject cubes = Instantiate (Cube) as GameObject;
cubes.AddComponent <CubeScript> ();
cubes.SetActive (true);
}
I'm invoking MakeCube() function every time when previous is destroyed. I ask this because I'm giving option in game that you can continue playing if you lost life. Current situation is that when you continue playing game, score isn't counting. For example. If I hit 5 cubes. I have score 5, then I lost "life". I press continue. I can hit cubes but they doesn't counting. When I hit 5 cubes it doesn't count to current score. But when I hit sixth cube it is counting from score 5 to 6.
Parent is a attribute of transform so you can play with transforms to get this. Well, in your case you can do something like,
void MakeCubes ()
{
GameObject cubes = Instantiate (Cube) as GameObject;
cubes.AddComponent <CubeScript> ();
// Replace YOUR_PARENT_GO from your parent GameObject
cubes.transform.parent = YOUR_PARENT_GO.transform;
cubes.SetActive (true);
}
You can sue transform.SetParent(). Unity docs: Transform.SetParent
You can set the parent for something that already exists in your hierarchy:
gameObject.transform.parent = GameObject.Find("Name of game object").transform;

Make object move from A to B and back again all the time

Hello and thanks for reading this.
I've created a little 2D game in Unity and I'm still very new to Unity.
I tried long and hard to search and check a guild / tutorial about how to make my "monster" move from A -> B and when he reach B then move back again. This he needs to keep doing all the time.
The Monster has a Box Collider and a Rigidbody and a "Destroyer" script so that if you run into him, you die.
I would really love to get a little help about how to create the monster movement.
Thanks alot.
This is quite simple, basically what you're looking for is a patrol feature which can be used like so:
GameObject A: (Cube, Cube Collider, Trigger = true, Disabled Mesh, Tag=PatrolPoint)
GameObject B: (Cube, Cube Collider, Trigger = true, Disabled Mesh, Tag=PatrolPoint)
GameObject C: npc that moves.
You would then need to create a script called "Patrol" that will handle the generation and ID of a patrol point. This script will be attatched to both GameObject A, and B.
using UnityEngine;
using System;
public class Patrol : MonoBehavior
{
public int patrolID;
public GameObject FindNextPoint()
{
GameObject base;
foreach(GameObject go in GameObject.FindGameObjectsWithTag("PatrolPoint"))
{
if(base == null && go.GetComponent<Patrol>().patrolID != patrolID)
{
base = go;
}
if(go.GetComponent<Patrol>().patrolID == (patrolID) + 1) {
return go;
}
}
// Return the first object found in the scene that isn't this object.
return base
}
}
Next you would need to use the OnTriggerEnter() function of unity in your script that's attatched to the player (or npc moving)-- http://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
using UnityEngine;
using System.Collections;
public class NpcScript : MonoBehaviour
{
private Vector3 targetLocation;
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "PatrolPoint")
{
setWalkTo(other.gameObject);
}
}
void setWalkTo(GameObject go)
{
targetLocation = go.GetComponent<Patrol>().FindNextPoint().transform.position;
}
}
You can have as many PatrolPoints as you want, just make sure to set the PatrolID variable to something different on each of them, the character will walk to them in order.
--- You have to add your own movement code, if you need help with that, let me know. Just move the gameobjects position towards targetLocation

Categories

Resources