Unity - infinite spawn issue - c#

I almost have my game ready, I want to create an infinite number of 2D squares for my 2D game. However, the following code I used does not work to spawn a single square infinitely.
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour
{
private GameObject[] locationsToSpawn;
private float counter = 0;
[SerializeField]
string[] listOfPossibleTags;
[SerializeField]
GameObject[] objectToSpawn;
[SerializeField]
float timeBetweenSpawns = 3.0f;
void Start()
{
locationsToSpawn = GameObject.FindGameObjectsWithTag("SpawnLocation");
}
void Update()
{
counter += Time.deltaTime;
if (counter > timeBetweenSpawns)
{
GameObject spawnedObject;
spawnedObject = Instantiate(objectToSpawn[Random.Range(0, objectToSpawn.Length)], locationsToSpawn[Random.Range(0, locationsToSpawn.Length)].transform.position, Quaternion.identity) as GameObject;
spawnedObject.gameObject.tag = listOfPossibleTags[Random.Range(0, listOfPossibleTags.Length)];
counter = 0;
}
}
}
Also, my game looks like the following image
So, what can I do to create an infinite number of squares falling? I'm very close to finishing the game.

Based on the information you provided in your comments you are putting a script on a gameobject that doesn't exist in your scene. If there is no instance of your game object in the game your script will never run. Put the script on something else that makes sense and it will run.
When trying to figure out whats wrong with your code use the debugger. You will be able to find your problems much easier!

Related

C# (Galaga Style Project) - Limit Projectile Prefab Clones based on Hierarchy

I am trying to practice creating a clone of Galaga following the same ruleset as the original. I am currently stuck trying to attempt a limit on the amount of cloned prefabs that can be in the scene at any one time, in the same way that Galaga's projectiles are limited to 2 on screen at any time. I want to make it so the player can shoot up to two projectiles, which destroy after 2 seconds or when they collide (this part is functioning), followed by not being able to shoot if two projectile clones are active and not yet destroyed in the hierarchy (Not working as I can instantiate projectiles over the limit of 2).
I have combed through Google for about 3 hours with no solutions that have worked for me, at least in the ways that I had attempted to implement them.
Thank y'all so much for the help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
public float moveSpeed = 1.0f;
public playerProjectile projectile;
public Transform launchOffset;
public int maxBullets = 0;
private GameObject cloneProjectile;
public Rigidbody2D player;
// Start is called before the first frame update
void Start()
{
player = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
MovePlayer();
PlayerShoot();
}
public void MovePlayer()
{
player.velocity = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * moveSpeed;
}
public void PlayerShoot()
{
if (Input.GetKeyDown(KeyCode.Z))
{
var cloneProjectile = Instantiate(projectile, launchOffset.position, launchOffset.rotation);
maxBullets++;
if (maxBullets >= 3)
{
Destroy(cloneProjectile, 0.1f);
maxBullets --;
return;
}
}
}
}
You could change the logic up a bit. An instance of the playerController class is active as long as the game is active, so it will know and retain the value of 'maxBullets' until you die or exit the program.
So instead, every time you click "z", the first thing you should do is run the check. If the current amount of live projectiles equals the maximum, have the logic 'return' and exit out of the method.

I need help for spawning enemies in unity 2d

I have problem spawning enemies in unity 2d. Enemies clones themselves too quickly and it lags. Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public Transform[] spawnPoints;
public GameObject enemy;
public float spawnTime = 5f;
public float spawnDelay = 3f;
// Use this for initialization
void Start () {
InvokeRepeating ("addEnemy", spawnDelay, spawnTime);
}
void addEnemy() {
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position,
spawnPoints[spawnPointIndex].rotation);
}
}
Oh, I am currently making a 2D game where I have to spawn enemies and here is what code I used, edited for you of course:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab;
public float interval = 100;
private float counter = 0;
// Update is called once per frame
void FixedUpdate()
{
counter += 1;
if(counter >= interval){
counter = 0;
Instantiate(enemyPrefab, transform.position,transform.rotation);
}
}
}
Simply create a new game object, put this script it, add the enemy prefab in the Game Object variable and you are set. You can edit the interval between each enemy with the interval variable. Good luck with your project :)
I'm assuming they are spawning more than every 3 seconds? Do you have multiple 'EnemySpawner' scripts attached to objects in the scene?
edit sounds like you have an ‘EnemySpawner’ script in your prefab, remove it from prefab and put it on a separate GameObject in your scene.
You should not as in the accepted answer use FixedUpdate for this! It uses 100 fixed update steps .. but who wants to calculate how long this actually takes?
By default fixed update step is 0.02s so 100 means 2 real-time seconds - but what if you change the fixed update step for any reason?
I would rather do it using a simple timer in Update:
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab;
// In seconds
[SerializeField]private float interval = 2f;
private float timer = 0f;
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if(timer >= interval){
timer = 0f;
Instantiate(enemyPrefab, transform.position,transform.rotation);
}
}
}
Actually what you had should also work! Depends of course also on the values you set via the Inspector.
BUT What I can see from the image you posted is: In enemy you referenced the object itself!
=> The next time there are 2 enemy instances including this spawner
=> The next time there are 4 enemy instances including this spawner
=> The next time there are 8 enemy instances ...
=> etc
Therefore they are called Enemy[Clone] then Enemy[Clone][Clone] then Enemy[Clone][Clone][Clone] etc so
Not sure if this was intended but I would rather put the spawner script on one single object in the scene and rather reference a prefab without an additional spawner script.

How do i fix my spawning script from randomly stopping the spawning of enemies?

I have a simple script that is supposed to spawn zombies with time delays that can be inputted. The script seems to work fine however, after I move my character for a while, the gameobject which is running the script stops spawning zombies.If my character stands still, the zombies will continue to spawn. The red arrow is pointing to the gameObject that is spawning the zombies.
using UnityEngine;
using System.Collections;
public class spawn : MonoBehaviour
{
public GameObject zombie;
public float delayTime = 4f;
IEnumerator Start()
{
var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
yield return new WaitForSeconds(delayTime);
StartCoroutine(Start());
}
}
Scene setup is as follows:
First separate your spawning function from your Start function to avoid confusion.
void Start()
{
StartCoroutine(SpawningRoutine());
}
Then you want your coroutine to continue spawning forever? You need a loop inside the coroutine. In the example below I made an infinite loop but you could have a counter for the number of zombies you want for example.
IEnumerator SpawningRoutine()
{
while(true)
{
var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
yield return new WaitForSeconds(delayTime);
}
}
Lastly remember to put this spawn script on an object that is not a zombie. Have a separate spawn object with only this script on it. You probably do this already.
Edit in response to logging:
Add a logging script to your zombie prefab like so:
private static int zombieCounter = 0;
void Start()
{
Debug.Log("Number of zombies spawned so far: " + zombieCounter++);
}
You don't really need to use coroutine for that, InvokeRepeating should be good enough. Also make sure your zombie prefab is private so it doesn't get replaced by other scripts
[SerializeField] private GameObject zombie;
float waitBeforeFirstSpawn = 0f;
float delayTime = 4f;
void Start()
{
InvokeRepeating("SpawnZombie", waitBeforeFirstSpawn, delayTime);
}
void SpawnZombie()
{
GameObject zombieGO = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
}

Using the LookAt() function in Unity

So I have an assignment that I have to do for school where an enemy shoots at the player in a gun type game. I have read about the LookAt() function in the Unity tutorials and used it to my knowledge of it. However it doesn't seem to be working. The following code is what I have so far:
public class EnemyControl : MonoBehaviour {
private Rigidbody rb;
public GameObject Bullet_Emitter2;
public GameObject EnemyBullet;
public float speedOfBullet;
private int score;
public Text countText;
public Text winText;
private GameObject Temporart_Bullet_Handler2;
public Transform player;
public Transform enemy;
void Start()
{
rb = GetComponent<Rigidbody>();
score = 0;
}
private void Update()
{
enemy.LookAt(player);
}
// Update is called once per frame
void FixedUpdate () {
int fire = Random.Range(0, 100);
if(fire == 0 || fire == 1 || fire == 5)
{
Temporart_Bullet_Handler2 = Instantiate(EnemyBullet, Bullet_Emitter2.transform.position, Bullet_Emitter2.transform.rotation) as GameObject;
Temporart_Bullet_Handler2.transform.Rotate(Vector3.right * 90);
Rigidbody Temporary_Rigid_Body;
Temporary_Rigid_Body = Temporart_Bullet_Handler2.GetComponent<Rigidbody>();
Temporary_Rigid_Body.AddForce(transform.up * speedOfBullet);
Destroy(Temporart_Bullet_Handler2, 20.0f);
}
}
}
The problem is my enemy now just looks at the ground instead of me and then just shoots downwards. Is there a way I can fix this? I have attached an image of what it looks like to a player playing the game?
Before putting in the LookAt() function my spaceman would just be stationary and fire bullets in a straight line but I need the AI to track the player instead of stationary. Is there another way to do this without using LookAt() or am I using this function wrong?
Thanks for the help in advance?
I would post this in comments but I can't yet because of low reputation
As Serlite pointed out, LookAt() only faces the GameObject's trasnform.forward (which is desired to be (0, 0, 1) when the object is not rotated) towards the target passed as argument.
To 'fix' this simply add an empty GameObject to your Hirarchy and set your AI object as its child
Empty GameObject
- AI GameObject (with your script)
Now you can set a global rotation for your object (Rotate the parent) in a way that the AI's forwards faces z+.

Object Shoots On x-z Axis

I actually have 2 issues. The first problem I have is that when I start my game all 4 cannons do their animation sequence for no reason, nothing happens. I'd like this to not happen. The second problem I have is the cannon ball that shoots out spawns on the floor and flies along the floor. Here is the code for the firing sequence:
using UnityEngine;
using System.Collections;
public class Cannon : MonoBehaviour {
public AudioClip sound;
public GameObject prefab;
public GameObject ejectPoint;
void Start () {
prefab = Resources.Load ("Cannon_Ball") as GameObject;
}
public void Fire () {
GameObject Cannon_Ball = Instantiate (prefab) as GameObject;
Cannon_Ball.transform.position = transform.position + ejectPoint.transform.forward * 2;
Rigidbody rd = Cannon_Ball.GetComponent<Rigidbody> ();
rd.velocity = ejectPoint.transform.forward * 130;
AudioSource.PlayClipAtPoint(sound, transform.position, 1);
GetComponent<Animation> ().Play ();
}
}
Here is a GIF of the problem:
fix 1: Uncheck 'Play Automatically' or find equal option in your Animator. I think after you start game, your Animator change his state from "Start" to "Shoot" because of bad conditions setting or even totally lake of conditions . If you paste here screenshot of your animator, that would be useful.
If you want to fix your second problem you should watch this video:
BRICK SHOOTER - Official Unity Tutorial

Categories