Method to stop enemies from spawning Unity5 - c#

I am developing a laser defender game.
Here is the main function responsible for spawning enemies. I have the variable waves set to 3. Then I want to destroy the position of the space ships in order to not allow them to spawn. The issue is when I start the game there are no ships at all.
if (AllMembersDead())
{
for (float i = 0; i < waves; i++)
{
SpawnUntilFull(); // number of waves to be spawned
}
Destroy(position);
}
Here is the picture of the gameobject I destroy:
Here are the function for SpawnUntilFull() and AllMembersDead() if needed.
bool AllMembersDead()
{
foreach(Transform childPositionGameObject in transform)
{
if (childPositionGameObject.childCount > 0)
{
return false;
}
}
return true;
}
void SpawnUntilFull()
{
Transform freePosition = NextFreePosition();
if (freePosition)
{
GameObject enemy = Instantiate(enemyPrefab, freePosition.transform.position, Quaternion.identity) as GameObject; // Instantiate (spawning or creating) enemy prefab (as gameobject assures that what its returning to us is no normal object but rather a game object)
enemy.transform.parent = freePosition; // the transform of whatever thing the enemy is attached to, and that would be the enemyFormation GameObject
}
if (NextFreePosition())
{
Invoke("SpawnUntilFull", spawnDelay);
}
}
I'm not sure what I'm doing wrong. Any guidance would be appreciated.

I think your AllMembersDead() function returns false because the childPositionGameObject you're looking at is the TotalPositions gameobject, hence SpawnUntilFull() is never called.
Try changing the function to point to the right parent, as such:
bool AllMembersDead()
{
foreach(Transform childPositionGameObject in position)
{
if (childPositionGameObject.childCount > 0)
{
return false;
}
}
return true;
}

Related

Detecting Enemies inside Area,Detecting Enemies inside Circle UNITY2D

im doing my first game and im trying to detect the enemies inside an circle area around my player.
i have two problems right now:
-When a start the game, the circlecollider and player collider is detected as enemies even when i use the compare tag "Enemy"
-My corroutine dont refresh every 2s, and only detect colliders one time when the game start
public class ItemDamage : MonoBehaviour
{
[SerializeField] int damage;
[SerializeField] Collider2D[] objectsInsideArea;
Vector2 radiusOfDamage;
int radius;
public void Start()
{
radiusOfDamage = new Vector2(radius, 0f);
StartCoroutine(DamageEnemy());
}
bool IsEnemy(string tag)
{
for (int i = 0; i < objectsInsideArea.Length; i++)
if (objectsInsideArea[i].gameObject.CompareTag("Enemy"))
{
Debug.Log("object {i} is an Enemy");
return true;
} else
{
Debug.Log("object {i}");
}
return false;
}
IEnumerator DamageEnemy()
{
objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
foreach (bool IsEnemy in objectsInsideArea)
{
Debug.Log("You damage the enemy");
}
yield return new WaitForSeconds(2);
}
}
For coroutine to repeat itself, it has to start itself in the end again like this:
IEnumerator DamageEnemy()
{
objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
foreach (bool IsEnemy in objectsInsideArea)
{
Debug.Log("You damage the enemy");
}
yield return new WaitForSeconds(2);
StartCoroutine(DamageEnemy());
}
Also instead of coroutine for this, you can use InvokeRepeating method.
You don't have to use a predefined array of objects, but rather use SphereRaycast method where you specify layer of objects to look for.
And your enemies can be located in the specific layer.
A Caroutine does not start it self.
For the other problem. objectsInsideArea is a Collider array and not a bool array. You cannot check it this way. Your code must look like this:
IEnumerator DamageEnemy()
{
while(someBoolOrTrue) {
objectsInsideArea = Physics2D.OverlapAreaAll(Vector2.zero, radiusOfDamage);
foreach (var collider in objectsInsideArea)
{
if(collider.tag.Equals("Enemy")) {
Debug.Log("You damage the enemy");
}
}
yield return new WaitForSeconds(2);
}
}

OnCollisionExit is called, but behaves strangely

I'm developing a 3d FPS game in Unity. At the moment I'm implementing a wall-running mechanic. The logic behind this is very simple - if player is pushing forward, and not grounded, and touching a wall, I constrain the Y/Z direction (but player can still run forward as I ignore the X direction though) and turn off gravity. It seems to work fine, a little bit clumsy but ok for me. Except, when the wall is left behind player is still able to run in mid-air until he runs out of inertia (here's the example: https://imgur.com/a/LtbWs9J). Here's the code:
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class WallRunning : MonoBehaviour
{
public AudioClip audioClip;
private CharacterMovement cm;
private Rigidbody rb;
private bool isJumping;
public bool isWall;
private bool playAudio;
private AudioSource audioSource;
public float energyLimit = 3.5f;
private void Start()
{
//Get attached components so we can interact with them in our script.
cm = GetComponent<CharacterMovement>();
rb = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
private void FixedUpdate()
{
bool jumpPressed = Input.GetButtonDown("Jump");
float verticalAxis = Input.GetAxis("Vertical");
//Check if the controller is grounded.
if (cm.Grounded)
{
isJumping = false;
isWall = false;
}
//Has the jump button been pressed.
if (jumpPressed)
{
StartCoroutine(Jumping());
}
//If we are pushing forward, and not grounded, and touching a wall.
if (verticalAxis > 0 && isJumping && isWall)
{
StartCoroutine(Energy());
//We constrain the Y/Z direction to defy gravity and move off the wall.
//But we can still run forward as we ignore the X direction.
rb.useGravity = false;
rb.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezeRotation;
//We also telegraph to the player by playing a sound effect on contact.
if (audioClip != null && playAudio == true)
{
audioSource.PlayOneShot(audioClip);
//We block more audio being played while we are on the wall.
playAudio = false;
}
}
else
{
StopCoroutine(Energy());
//We need to make sure we can play audio again when touching the wall.
playAudio = true;
rb.useGravity = true;
rb.constraints = RigidbodyConstraints.FreezeRotation;
}
}
void OnCollisionEnter(Collision other)
{
//Are we touching a wall object?
if (other.gameObject.CompareTag("Walls"))
{
isWall = true;
}
}
void OnCollisionExit(Collision other)
{
//Did we stop touching the wall object?
if (!other.gameObject.CompareTag("Walls"))
{
isWall = false;
}
}
IEnumerator Jumping()
{
//Check for 5 frames after the jump button is pressed.
int frameCount = 0;
while (frameCount < 5)
{
frameCount++;
//Are we airbourne in those 5 frames?
if (!cm.Grounded)
{
isJumping = true;
}
yield return null;
}
}
IEnumerator Energy()
{
yield return new WaitForSeconds(energyLimit);
isWall = false;
}
}
Notice: walls have box colliders on them ("Is Trigger" checkbox is unchecked), and player has non-kinematic rigidbody and capsule collider attached. Walls aren't marked as "static" and assigned to Default layer, while player is assigned to the Player layer.
What am I doing wrong? I'm sure I screwed up with the code, but can't figure out the problem.
Replace
void OnCollisionExit(Collision other)
{
//Did we stop touching the wall object?
if (!other.gameObject.CompareTag("Walls"))
{
isWall = false;
}
}
With
void OnCollisionExit(Collision other)
{
//Did we stop touching the wall object?
if (other.gameObject.CompareTag("Walls"))
{
isWall = false;
}
}

How can I add a particle system while my player is dead?

I have a death animation already. I want a particle system particleRed to start along with the death animation. I have a private variable particleRed and I have initiated it in the awake function.
What should I do now?
using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class CharacterController2D : MonoBehaviour {
// player controls
[Range(0.0f, 10.0f)] // create a slider in the editor and set limits on moveSpeed
public float moveSpeed = 3f;
public float jumpForce = 600f;
// player health
public int playerHealth = 1;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
// player can move?
// we want this public so other scripts can access it but we don't want to show in editor as it might confuse designer
[HideInInspector]
public bool playerCanMove = true;
// SFXs
public AudioClip coinSFX;
public AudioClip deathSFX;
public AudioClip fallSFX;
public AudioClip jumpSFX;
public AudioClip victorySFX;
// private variables below
// store references to components on the gameObject
Transform _transform;
Rigidbody2D _rigidbody;
Animator _animator;
AudioSource _audio;
ParticleSystem particleRed;
// hold player motion in this timestep
float _vx;
float _vy;
// player tracking
bool facingRight = true;
bool isGrounded = false;
bool isRunning = false;
bool _canDoubleJump = false;
// store the layer the player is on (setup in Awake)
int _playerLayer;
// number of layer that Platforms are on (setup in Awake)
int _platformLayer;
void Awake () {
// get a reference to the components we are going to be changing and store a reference for efficiency purposes
_transform = GetComponent<Transform> ();
_rigidbody = GetComponent<Rigidbody2D> ();
if (_rigidbody==null) // if Rigidbody is missing
Debug.LogError("Rigidbody2D component missing from this gameobject");
_animator = GetComponent<Animator>();
if (_animator==null) // if Animator is missing
Debug.LogError("Animator component missing from this gameobject");
_audio = GetComponent<AudioSource> ();
if (_audio==null) { // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
_audio = gameObject.AddComponent<AudioSource>();
}
particleRed = GetComponent<ParticleSystem>();
// determine the player's specified layer
_playerLayer = this.gameObject.layer;
// determine the platform's specified layer
_platformLayer = LayerMask.NameToLayer("Platform");
}
// this is where most of the player controller magic happens each game event loop
void Update()
{
// exit update if player cannot move or game is paused
if (!playerCanMove || (Time.timeScale == 0f))
return;
// determine horizontal velocity change based on the horizontal input
_vx = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
// Determine if running based on the horizontal movement
if (_vx != 0)
{
isRunning = true;
} else {
isRunning = false;
}
// set the running animation state
_animator.SetBool("Running", isRunning);
// get the current vertical velocity from the rigidbody component
_vy = _rigidbody.velocity.y;
// Check to see if character is grounded by raycasting from the middle of the player
// down to the groundCheck position and see if collected with gameobjects on the
// whatIsGround layer
isGrounded = Physics2D.Linecast(_transform.position, groundCheck.position, whatIsGround);
// Allow Double Jump after grounded
if (isGrounded)
{
_canDoubleJump = true;
}
// Set the grounded animation states
_animator.SetBool("Grounded", isGrounded);
if (isGrounded && CrossPlatformInputManager.GetButtonDown ("Jump")) { // If grounded AND jump button pressed, then allow the player to jump
DoJump ();
} else if (_canDoubleJump && CrossPlatformInputManager.GetButtonDown ("Jump"))
{
DoJump();
// double jumo can be possible once
_canDoubleJump = false;
}
// If the player stops jumping mid jump and player is not yet falling
// then set the vertical velocity to 0 (he will start to fall from gravity)
if(CrossPlatformInputManager.GetButtonUp("Jump") && _vy>0f)
{
_vy = 0f;
}
// Change the actual velocity on the rigidbody
_rigidbody.velocity = new Vector2(_vx * moveSpeed, _vy);
// if moving up then don't collide with platform layer
// this allows the player to jump up through things on the platform layer
// NOTE: requires the platforms to be on a layer named "Platform"
Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f));
}
// Checking to see if the sprite should be flipped
// this is done in LateUpdate since the Animator may override the localScale
// this code will flip the player even if the animator is controlling scale
void LateUpdate()
{
// get the current scale
Vector3 localScale = _transform.localScale;
if (_vx > 0) // moving right so face right
{
facingRight = true;
} else if (_vx < 0) { // moving left so face left
facingRight = false;
}
// check to see if scale x is right for the player
// if not, multiple by -1 which is an easy way to flip a sprite
if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
localScale.x *= -1;
}
// update the scale
_transform.localScale = localScale;
}
// if the player collides with a MovingPlatform, then make it a child of that platform
// so it will go for a ride on the MovingPlatform
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag=="MovingPlatform")
{
this.transform.parent = other.transform;
}
}
// if the player exits a collision with a moving platform, then unchild it
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag=="MovingPlatform")
{
this.transform.parent = null;
}
}
//make the player jump
void DoJump()
{
// reset current vertical motion to 0 prior to jump
_vy = 0f;
// add a force in the up direction
_rigidbody.AddForce (new Vector2 (0, jumpForce));
// play the jump sound
PlaySound(jumpSFX);
}
// do what needs to be done to freeze the player
void FreezeMotion() {
playerCanMove = false;
_rigidbody.isKinematic = true;
}
// do what needs to be done to unfreeze the player
void UnFreezeMotion() {
playerCanMove = true;
_rigidbody.isKinematic = false;
}
// play sound through the audiosource on the gameobject
void PlaySound(AudioClip clip)
{
_audio.PlayOneShot(clip);
}
// public function to apply damage to the player
public void ApplyDamage (int damage) {
if (playerCanMove) {
playerHealth -= damage;
if (playerHealth <= 0) { // player is now dead, so start dying
PlaySound(deathSFX);
StartCoroutine (KillPlayer ());
}
}
}
// public function to kill the player when they have a fall death
public void FallDeath () {
if (playerCanMove) {
playerHealth = 0;
PlaySound(fallSFX);
StartCoroutine (KillPlayer ());
}
}
// coroutine to kill the player
IEnumerator KillPlayer()
{
if (playerCanMove)
{
// freeze the player
FreezeMotion();
// play the death animation
_animator.SetTrigger("Death");
// After waiting tell the GameManager to reset the game
yield return new WaitForSeconds(2.0f);
if (GameManager.gm) // if the gameManager is available, tell it to reset the game
GameManager.gm.ResetGame();
else // otherwise, just reload the current level
Application.LoadLevel(Application.loadedLevelName);
}
}
public void CollectCoin(int amount) {
PlaySound(coinSFX);
if (GameManager.gm) // add the points through the game manager, if it is available
GameManager.gm.AddPoints(amount);
}
// public function on victory over the level
public void Victory() {
PlaySound(victorySFX);
FreezeMotion ();
_animator.SetTrigger("Victory");
if (GameManager.gm) // do the game manager level compete stuff, if it is available
GameManager.gm.LevelCompete();
}
// public function to respawn the player at the appropriate location
public void Respawn(Vector3 spawnloc) {
UnFreezeMotion();
playerHealth = 1;
_transform.parent = null;
_transform.position = spawnloc;
_animator.SetTrigger("Respawn");
}
public void EnemyBounce ()
{
DoJump ();
}
}
I suggest making a empty game object prefab that holds the particle system. Then when you want to use the particle system, just instantiate the object. That is the easiest way i've found to go about it, and its rather versatile. Another way is, you could make the empty game object a child of your player, and then activate it when you want to use it. The second way isn't as ideal, but will get the job done too.
For the ParticleSystem component that you have added to the gameObject, set the enabled property to false by unchecking the enabled checkbox on the component.
Then in the KillPlayer function
particleRed.enabled = true;
Additionally you can ensure it is disabled in the Awake function by setting it to false.

Prefab doesnot activate when collide with object

I'm making a project and there is a problem that I am facing.
I have two gameObject with 2D colliders (coming from a prefab) which moves right to left. When they touch each other they deactivate.
I also have an empty game object in which i add a script Respawner which randomly generates obstacles.
The problem is when they touch each other once, they never get re-activated again.
Respawner Empty GameObject :
Border :
Prefabs :
Respawn Script:
public class Respawn : MonoBehaviour {
[SerializeField]
private GameObject[] obstacles;
private List<GameObject> listname = new List<GameObject>();
void Awake(){
InitilizeObstacle();
}
void Start() {
StartCoroutine(RandomObstacleSpawn());
}
void InitilizeObstacle(){
int index = 0;
for (int i=0; i<obstacles.Length * 3 ; i++) {
GameObject obj = Instantiate(obstacles[index],new Vector3(transform.position.x,transform.position.y,-2f),Quaternion.identity) as GameObject;
listname.Add(obj);
listname[i].SetActive(false);
index++;
if(index==obstacles.Length){
index =0;
}
}
}
void shuffle(){
for (int i=0; i<listname.Count; i++) {
GameObject temp = listname [i];
int random = Random.Range (i, listname.Count);
listname [i] = listname [random];
listname [random] = temp;
}
}
IEnumerator RandomObstacleSpawn(){
yield return new WaitForSeconds(Random.Range(1.5f,2.5f));
int index = Random.Range (0, listname.Count);
while (true) {
if(!listname[index].activeInHierarchy){
listname[index].SetActive(true);
listname[index].transform.position = new Vector3(transform.position.x,transform.position.y,-2f);
break;
} else {
index = Random.Range(0,listname.Count);
}
StartCoroutine(RandomObstacleSpawn());
}
}
}
Script attach to prefab for move:
public class ObstacleMove : MonoBehaviour {
private float speed = -1.25f;
void Start() { }
void Update() {
Vector3 pos = transform.position;
pos.x += speed * Time.deltaTime;
transform.position = pos;
}
}
Scripts attach to prefab for touch border:
public class BorderTouch : MonoBehaviour {
void OnTriggerEnter2D(Collider2D target){
if(target.tag=="Border"){
gameObject.SetActive(false);
}
}
}
New answer based on new question:
If you want to make things happen AFTER the collision. Put a script on Border:
using UnityEngine;
using System.Collections;
public class borderListener : MonoBehaviour {
public Respawn rS;
void OnTriggerEnter2D(Collider2D target){
rS.spawnIt ();
}
}
On Unity Editor, drag the Respawn object to the Border Script on hierarchy.
Do not skip this step or things won't work!
On Respawn script, remove the last StartCoroutine(RandomObstacleSpawn()); line on IEnumerator RandomObstacleSpawn() method. And create a public method (to access from other script) anywhere inside Respawn script:
public void spawnIt(){
StartCoroutine(RandomObstacleSpawn());
}
Old answer based on old code:
From what I see on your package:
while (true) { //A
if(!listname[index].activeInHierarchy){
//B
listname[index].SetActive(true);
listname[index].transform.position = new Vector3(transform.position.x,transform.position.y,-2f);
break; //C
} else {
index = Random.Range(0,listname.Count);
}
StartCoroutine(RandomObstacleSpawn()); //D
}
I am a lil noob, I will try my best to help. But this piece of code makes me wonder:
while(true) what? what is true? (EDIT: found some observation bellow)
The code seem to do this path:
Go inside the while loop (A)
Go at the first option in if statement (B)
Go to the line break; (C)
Never reaches the StartCoroutine (D) > that is why it does not activate again.
If you try and put a StartCoroutine(RandomObstacleSpawn()); before the break; you probably will get an Unity crash. What if you take off the while statement at all? You need to adjust time of yield tho.
This is the code I would use:
IEnumerator RandomObstacleSpawn(){
yield return new WaitForSeconds(Random.Range(3.5f,4.5f));
int index = Random.Range (0, listname.Count);
if(!listname[index].activeInHierarchy){
listname[index].SetActive(true);
listname[index].transform.position = new Vector3(transform.position.x,transform.position.y,-2f);
}else{
index = Random.Range(0,listname.Count);
}
StartCoroutine(RandomObstacleSpawn());
}
EDIT: about the while(true) I've manage to find more information about this concept here: R, How does while (TRUE) work?
But still... the break; on the code is really making the Access to StartCoroutine(RandomObstacleSpawn()); unreachable .
The problem you are seeing is fairly common, when the following code is executed gameObject.SetActive(false); it deactivate everything on that gameObject.
Thus, the next time they would have collided will never be triggered.
I'm not sure what you want to achieve for the behaviour, but if you just want to hide the gameObjects you could disable the Renderer component instead.
gameObject.GetComponent<SpriteRenderer>().enable = false;
And switch it to true when needed.
That's why we must be carefull when we use SetActive(false) on gameObject in Unity.

Verifying there is no collision with a certain object after clicking it

I'm having trouble creating a way to check if the Player is NOT colliding with a certain 'waypoint' if I click that waypoint. I've set up 7 waypoints which the player will want to be able to move to.
Now I'm trying to write a piece of script that checks that AFTER the waypoint is clicked (onMouseDown) if there's a collision with the player. Because if that's the case it won't calculate the position to move to.
public class WayPointPositioner : MonoBehaviour {
private Vector3 wayPointPosition;
public GameObject playercheck;
//Check if object is clicked
void OnMouseDown ()
{
Debug.Log ("Object Clicked " + GameObject.name);
// Check if collision occurs with playercheck
OnCollisionEnter(playercheck != Collision)
{
// If its the player, then return a new position for the player to move to for walking
// Else debug that its not so
if (playercheck.gameObject.CompareTag("Player"))
{
Debug.Log ("Object not colliding and retrieving position");
wayPointPosition = new Vector3 (GameObject.X, GameObject.Y, 10);
wayPointPosition = Camera.main.ScreenToWorldPoint(wayPointPosition);
}
else
{
Debug.Log ("Object is colliding, no movement needed");
}
}
}
}
Now I've already figured out that OnCollisionEnter will not work. Because it requires the void-statement before it for it to function. However I have no clue how else I am able to do this.
I would just compare the position of the player and the way point. If equal then the player is there otherwise move to the way point. Hope I understand the problem right.
Managed to fix it. Was just being an idiot.
Key is to use both functionalities, SEPERATELY. So I divided the tasks of checking for Mousedown and checking if the place is occupied by creating a seperate variable to ask true of false from to check it all.
public class WayPointPositioner : MonoBehaviour {
private Vector3 wayPointPosition;
private bool checkPlayerWaypointCollision;
void Start()
{
wayPointPosition = transform.position;
}
void OnTriggerStay2D (Collider2D other)
{
if (other.gameObject.name == "Player")
{
checkPlayerWaypointCollision = true;
}
else
{
checkPlayerWaypointCollision = false;
}
}
//Check if object is clicked
void OnMouseDown ()
{
// If its the player, then return a new position for the player to move to for walking
// Else debug that its not so
if (checkPlayerWaypointCollision == false)
{
Debug.Log ("Object not colliding and retrieving position");
transform.position = new Vector3 (transform.position.x, transform.position.y, 10);
wayPointPosition = Camera.main.ScreenToWorldPoint(wayPointPosition);
}
else
{
Debug.Log ("Object is colliding, no movement needed");
}
}
}

Categories