Hello I want to create badges like in flappy bird , I put images in UI images like GameObjects. But it show me only one image of 3 images Please Please Help Out! And HighScore works , it rewrites when I get Higher score , but don't know why images won't change :(
Sorry For bad english
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
private float score = 0f;
public Text Scoretext;
public MenuController deathmenu;
public GameObject IntroGUI, DeathGUI, Canvas;
public GameObject[] medals;
public GameObject medale;
void Start()
{
medale.SetActive(false);
foreach(GameObject m in medals)
{
m.SetActive(true);
}
}
void Update()
{
//handle back key in Windows Phone
if (Input.GetKeyDown(KeyCode.Escape))
Application.Quit();
if (GameStateManager.GameState == GameState.Intro)
{if (WasTouchedOrClicked())
{
GameStateManager.GameState = GameState.Playing;
IntroGUI.SetActive(false);
Canvas.SetActive(true);
}
}
else if (GameStateManager.GameState == GameState.Playing)
{
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
if(PlayerPrefs.GetFloat("Scoretext") > 0)
{
medals[0].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 2)
{
medals[1].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 5)
{
medals[2].SetActive(true);
}
medale.SetActive(true);
deathmenu.ToggleEndMenu(score);
}
}
In Image you can see my GameObjects and Etc.
I updated the code but still doesnt work
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
private float score = 0f;
public Text Scoretext;
public MenuController deathmenu;
public GameObject IntroGUI, DeathGUI, Canvas;
public GameObject[] medals;
public GameObject medale;
void Start()
{
medale.SetActive(true);
}
void Update()
{
//handle back key in Windows Phone
if (Input.GetKeyDown(KeyCode.Escape))
Application.Quit();
if (GameStateManager.GameState == GameState.Intro)
{
if (WasTouchedOrClicked())
{
GameStateManager.GameState = GameState.Playing;
IntroGUI.SetActive(false);
Canvas.SetActive(true);
medale.SetActive(false);
}
}
else if (GameStateManager.GameState == GameState.Playing)
{
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
deathmenu.ToggleEndMenu(score);
}
}
void FixedUpdate()
{
//just jump up and down on intro screen
if (GameStateManager.GameState == GameState.Intro)
{
}
else if
(GameStateManager.GameState == GameState.Playing || GameStateManager.GameState == GameState.Dead)
{
}
}
bool WasTouchedOrClicked()
{
if (Input.GetButtonUp("Jump") || Input.GetMouseButtonDown(0) ||
(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
return true;
else
return false;
}
void OnCollisionEnter2D(Collision2D col)
{
if (GameStateManager.GameState == GameState.Playing)
{
if (col.gameObject.tag == "CARS")
{
PlayerDies();
}
}
}
void PlayerDies()
{
GameStateManager.GameState = GameState.Dead;
if (PlayerPrefs.GetFloat("Scoretext") > 0)
{
medals[0].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 2)
{
medals[1].SetActive(true);
}
else if
(PlayerPrefs.GetFloat("Scoretext") > 5)
{
medals[2].SetActive(true);
}
}
}
Turns out the stuff below is not enough to let your stuff work, you need to change medale.SetActive(false); to medale.SetActive(true); because this is the parent object which your medals are in.
You don't set the Scoretext anywhere so look at the score instead of the scoretext.
So you get:
score += Time.deltaTime;
Scoretext.text = ((int)score).ToString();
if (PlayerPrefs.GetFloat("Highscore") < score)
PlayerPrefs.SetFloat("Highscore", score);
if(score > 0)
{
medals[0].SetActive(true);
}
else if
(score > 2)
{
medals[1].SetActive(true);
}
else if
(score > 5)
{
medals[2].SetActive(true);
}
Also, why are you setting them active at the start?
Related
I wanted to add multiplayer to my game but i quickly faced many many problems, i cant find any clear solution online. i made a weapon script where the player can shoot and reload.
problems:
when i shoot, on 1 screen both players shoot, but at the other screen nothing happens
when i swap weapons, on 1 screen both players swap weapons, on the second screen nothing happens
note: im still a complete beginner so go easy on me please :)) thanks!
weapon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Photon.Pun;
public class weaponScript : MonoBehaviour
{
public weaponSO weaponStats;
public GameObject reloadingText;
public TMP_Text ammoValue;
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 2f;
public bool isShooting;
public float pistolDamage;
public int currentAmmoClip = 1;
public int maxAmmoClip;
public int currentReserve = 1;
public int maxReserve;
public float reloadTime = 2f;
public bool isReloading = false;
public int bulletsShot;
public float startingDamage;
PhotonView view;
public void Start()
{
view = GetComponent<PhotonView>();
if(view.IsMine)
{
view.RPC("Update", RpcTarget.AllBuffered);
}
WeaponStats();
currentAmmoClip = maxAmmoClip;
currentReserve = maxReserve;
bulletsShot = maxAmmoClip - currentAmmoClip;
isShooting = false;
weaponStats.damage = startingDamage;
}
[PunRPC]
public void Update()
{
ammoValue.text = currentAmmoClip.ToString("0") + "/" + currentReserve.ToString("0");
if (Input.GetKeyDown(KeyCode.R))
{
if(currentReserve <= 0)
{
return;
}
if (currentAmmoClip == maxAmmoClip && !isReloading)
{
return;
}
else
{
StartCoroutine(Reload());
return;
}
}
if(Input.GetButtonDown("Fire1") && currentAmmoClip >= 1)
{
if(isReloading == false)
{
bulletsShot += 1;
currentAmmoClip -= 1;
isShooting = true;
Shoot();
FindObjectOfType<AudioManager>().Play("shot1");
return;
}
}
if(isReloading)
return;
if(currentAmmoClip <= 0 && currentReserve >= 1)
{
StartCoroutine(Reload());
return;
}
}
IEnumerator Reload()
{
reloadingText.SetActive(true);
isReloading = true;
yield return new WaitForSeconds(reloadTime);
if(currentReserve <= bulletsShot)
{
currentAmmoClip += currentReserve;
currentReserve = 0;
}
else
{
currentReserve -= bulletsShot;
currentAmmoClip = maxAmmoClip;
}
bulletsShot = 0;
reloadingText.SetActive(false);
isReloading = false;
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
public void WeaponStats()
{
pistolDamage = weaponStats.initialDamage;
maxAmmoClip = weaponStats.maxAmmoClip;
maxReserve = weaponStats.maxReserve;
reloadTime = weaponStats.reloadTime;
bulletForce = weaponStats.bulletForce;
startingDamage = weaponStats.initialDamage;
}
}
weapon holder:
using UnityEngine;
public class WeaponHolder : MonoBehaviour
{
public int selectedWeapon = 0;
void Start()
{
SelectWeapon();
}
void Update()
{
if(FindObjectsOfType<weaponScript>()[0].isReloading == true)
{
return;
}
else
{
switchWeapon();
}
}
public void switchWeapon()
{
int previousSelectedWeapon = selectedWeapon;
if(Input.GetAxis("Mouse ScrollWheel") > 0f)
{
if(selectedWeapon >= transform.childCount - 1)
{
selectedWeapon = 0;
}
else
{
selectedWeapon++;
}
}
if(Input.GetAxis("Mouse ScrollWheel") < 0f)
{
if(selectedWeapon <= 0)
{
selectedWeapon = transform.childCount - 1;
}
else
{
selectedWeapon--;
}
}
if(previousSelectedWeapon != selectedWeapon)
{
SelectWeapon();
}
}
public void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform)
{
if(i == selectedWeapon)
{
weapon.gameObject.SetActive(true);
}
else
{
weapon.gameObject.SetActive(false);
}
i++;
}
}
}
i tried adding
if(view.IsMine == true)
{
Debug.Log("true");
}
else
{
Debug.Log("false");
}
but nothing happened and i couldnt shoot anymore. thanks for reading
The problem is you don't sync anything in your game. This means the other computer can't know what it has to do.
Whenever you want to sync something you have to call an RPC function.
Maybe watch some tutorials about how to do this properly and how to set up a simple multiplayer lobby.
EDIT:
What the other comments above mentioned with .IsMine is true, but you're doing it wrong. You have to call this in start or awake and whenever the view is not yours you disable the camera of the person only and disable shooting. Its important to only do this on your computer! If you are not doing everyone will shoot when you press Shoot and everyone will walk when you walk.
I am using Destroy(Corazones[0].gameObject); to destroy 5 hearts in an array, but I need to restore them when the player gets another heart. I already have the collider that increases lives +1 and it works, but I do not know how to respawn the heart that represents that life.
The hearts get destroyed when the player gets Hit(); but I also need for the hearts to get restored with Vida(); which increases the live +1
Thanks for your help!
This is the way the hearts look
My code uses spanish words.
PD: I know my code is a mess, but works for the other stuff.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.UI;
public class DixonMovement : MonoBehaviour
{
public GameObject PildoraPrefab;
public float Speed;
public float JumpForce;
public AudioClip Golpe;
public AudioClip Salto;
public AudioClip Muerte;
public AudioClip Caida;
public GameObject[] Corazones;
private Rigidbody2D Rigidbody2D;
private Animator Animator;
private float Horizontal;
private bool Grounded;
private float LastShoot;
private int Health = 5;
public bool YaSono = false;
[Header("IFrame Stuff")]
public Color flashColor;
public Color regularColor;
public float flashDuration;
public int numberOfFlashes;
public Collider2D triggerCollider;
public SpriteRenderer mySprite;
float timer;
bool invencible = false;
private void Start()
{
Rigidbody2D = GetComponent<Rigidbody2D>();
Animator = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
invencible = false;
}
Horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
if (Horizontal < 0.0f) transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f);
else if (Horizontal > 0.0f) transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
Animator.SetBool("Caminar", Horizontal != 0.0f);
Debug.DrawRay(transform.position, Vector3.down * 0.5f, Color.red);
if (Physics2D.Raycast(transform.position, Vector3.down, 0.5f))
{
Grounded = true;
}
else Grounded = false;
if (CrossPlatformInputManager.GetButtonDown("Jump") && Grounded)
{
Jump();
}
if (Input.GetKeyDown(KeyCode.W) && Grounded)
{
Jump();
}
if (Input.GetKey(KeyCode.Space) && Time.time > LastShoot + 0.25f)
{
Shoot();
LastShoot = Time.time;
}
if (CrossPlatformInputManager.GetButtonDown("Shoot") && Time.time > LastShoot + 0.50f)
{
Shoot();
LastShoot = Time.time;
}
/* if (CrossPlatformInputManager.GetButtonDown("Vertical") && Time.time > LastShoot + 0.50f)
{
Shoot();
LastShoot = Time.time;
}*/
if (transform.position.y <= -2)
{
Fall();
}
}
private void FixedUpdate()
{
Rigidbody2D.velocity = new Vector2(Horizontal * Speed, Rigidbody2D.velocity.y);
}
private void Jump()
{
Rigidbody2D.AddForce(Vector2.up * JumpForce);
Camera.main.GetComponent<AudioSource>().PlayOneShot(Salto);
}
private void Shoot()
{
Vector3 direction;
if (transform.localScale.x == 1.0f) direction = Vector3.right;
else direction = Vector3.left;
GameObject pastilla = Instantiate(PildoraPrefab, transform.position + direction * 0.40f, Quaternion.identity);
pastilla.GetComponent<Pastilla>().SetDirection(direction);
}
**public void Hit()
{
Health -= 1;
if (Health > 0)
{
StartCoroutine(FlashCo());
}
if (Health < 1)
{
Destroy(Corazones[0].gameObject);
}
else if (Health < 2)
{
Destroy(Corazones[1].gameObject);
}
else if (Health < 3)
{
Destroy(Corazones[2].gameObject);
}
else if (Health < 4)
{
Destroy(Corazones[3].gameObject);
}
else if (Health < 5)
{
Destroy(Corazones[4].gameObject);
}
if (Health > 0)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Golpe);
}**
if (Health == 0)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Muerte);
Animator.SetTrigger("Muerte");
if (Grounded == false)
{
Rigidbody2D.bodyType = RigidbodyType2D.Dynamic;
Rigidbody2D.gravityScale = 2;
}
else
{
Rigidbody2D.bodyType = RigidbodyType2D.Static;
}
}
}
public void Fall()
{
if (transform.position.y <= -1)
{
Rigidbody2D.AddForce(Vector2.up * 60);
if (!YaSono)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Caida);
YaSono = true;
}
Animator.SetTrigger("Muerte");
Health = 0;
Destroy(Rigidbody2D, 2);
Destroy(Corazones[0].gameObject);
Destroy(Corazones[1].gameObject);
Destroy(Corazones[2].gameObject);
Destroy(Corazones[3].gameObject);
Destroy(Corazones[4].gameObject);
Invoke("RestartLevel", 2);
}
}
public void Vida()
{
if (Health >=5) { } else { Health += 1; }
}
public void Bounce()
{
Rigidbody2D.AddForce(Vector2.up * 300);
}
void Invencible()
{
timer = 1;
if (timer > 0)
{
invencible = true;
}
}
private IEnumerator FlashCo()
{
int temp = 0;
triggerCollider.enabled = false;
while (temp < numberOfFlashes)
{
mySprite.color = flashColor;
yield return new WaitForSeconds(flashDuration);
mySprite.color = regularColor;
yield return new WaitForSeconds(flashDuration);
temp++;
}
triggerCollider.enabled = true;
}
private void RestartLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Instead of using Destroy(Corazones[0].gameObject) you could use Corazones[0].gameObject.setActive(false) or simply Corazones[0].setActive(false) since the array already contains GameObjects.
This would preserve the GameObject while all of its components and children would be inactivated including its Renderer which would make it disappear.
Then later when you need it you could reactivate it using Corazones[0].setActive(true).
I am working on setting up a simple little AI for a character in my game. For some reason I am having major problems getting animations to play while using the NavMeshAgent and I do not understand why. This is a waypoint system that I pooled off Unity API, and I can't even seem to get this working. I am hoping that if someone can give me some input on this if might clear some other things up as well. I am really lost here and would appreciate any input. The code on the bottom all works until it hits Patrol and then the player moves without animating. I feel like there is something more i need to know about navmesh's maybe. Or a lot more I need to know about programming in general.
e// Patrol.cs
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
public class Enemy_Patrol : MonoBehaviour
{
public Transform[] points;
public Animator anim;
private int destPoint = 0;
private NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint()
{
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
anim.SetBool("WalkForwards", true);
anim.SetBool("IsIdle", false);
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
void Update()
{
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}
// Code i wrote to handle following chasing etc.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AI_Tester : MonoBehaviour
{
private float patrolSpeed = .2f;
public NavMeshAgent agent;
public GameObject[] waypoints;
private int waypointInd = 0;
public Transform player;
static Animator anim;
public SealForce_DestructableObjects destructableObjects;
public Transform enemy;
// Use this for initialization
void Start()
{
anim = GetComponentInChildren<Animator>();
agent = GetComponent<NavMeshAgent>();
destructableObjects = GetComponent<SealForce_DestructableObjects>();
waypoints = GameObject.FindGameObjectsWithTag("waypoints");
waypointInd = Random.Range(0, waypoints.Length);
}
void AIMovements()
{
if (Vector3.Distance(player.position, this.transform.position) <= 30)
{
Vector3 direction = player.position - this.transform.position;
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction), 0.1f);
if (direction.magnitude > 15)
{
MoveToFiringRange();
}
if (direction.magnitude <= 15)
{
AttackPlayer();
}
}
else if (Vector3.Distance(player.position, this.transform.position) > 30)
{
WaitingOnAction();
}
}
public void Update()
{
AIMovements();
}
public void AttackPlayer()
{
anim.SetTrigger("IsAttacking");
anim.SetBool("IsIdle", false);
anim.SetBool("RunForwards", false);
}
public void MoveToFiringRange()
{
this.transform.Translate(0, 0, 0.04f);
anim.SetBool("RunForwards", true);
anim.SetBool("IsIdle", false);
anim.ResetTrigger("IsAttacking");
}
public void WaitingOnAction()
{
anim.SetBool("IsIdle", true);
anim.SetBool("RunForwards", false);
StartCoroutine("BackToPatrol");
}
//program works fine all the up to here. The only thing wrong with patrol is no animation.
IEnumerator BackToPatrol()
{
yield return new WaitForSeconds(5);
anim.SetBool("IsIdle", false);
Patrol();
}
public void Patrol()
{
Debug.Log("In Patrol");
agent.speed = patrolSpeed;
if (Vector3.Distance(this.transform.position, waypoints[waypointInd].transform.position) >= 2)
{
agent.SetDestination(waypoints[waypointInd].transform.position);
anim.SetBool("WalkForwards", true);
}
if (Vector3.Distance(this.transform.position, waypoints[waypointInd].transform.position) <= 2)
{
waypointInd += 1;
if (waypointInd > waypoints.Length)
{
waypointInd = 0;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AI_Tester : MonoBehaviour
{
public bool isPatrolling;
private float patrolSpeed = 1.5f;
public NavMeshAgent agent;
public GameObject[] waypoints;
private int waypointInd = 0;
public Transform player;
static Animator anim;
//public SealForce_DestructableObjects destructableObjects;
//public Transform enemy;
// Use this for initialization
void Start()
{
anim = GetComponentInChildren<Animator>();
agent = GetComponent<NavMeshAgent>();
//destructableObjects = GetComponent<SealForce_DestructableObjects>();
waypoints = GameObject.FindGameObjectsWithTag("waypoints");
waypointInd = Random.Range(0, waypoints.Length);
}
void AIMovements()
{
if (Vector3.Distance(player.position, this.transform.position) <= 30)
{
Vector3 direction = player.position - this.transform.position;
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction), 0.1f);
if (direction.magnitude > 15)
{
//StopCoroutine("BackToPatrol");
StopCoroutine("Patrol");
isPatrolling = false;
MoveToFiringRange();
}
if (direction.magnitude <= 15)
{
//StopCoroutine("BackToPatrol");
StopCoroutine("Patrol");
isPatrolling = false;
AttackPlayer();
}
}
else if (Vector3.Distance(player.position, this.transform.position) > 30 && !isPatrolling)
{
//StopCoroutine("BackToPatrol");
StopCoroutine("Patrol");
WaitingOnAction();
}
}
public void Update()
{
AIMovements();
}
public void AttackPlayer()
{
anim.SetTrigger("IsAttacking");
anim.SetBool("IsIdle", false);
anim.SetBool("RunForwards", false);
}
public void MoveToFiringRange()
{
this.transform.Translate(0, 0, 0.04f);
anim.SetBool("RunForwards", true);
anim.SetBool("IsIdle", false);
anim.ResetTrigger("IsAttacking");
}
public void WaitingOnAction()
{
anim.SetBool("IsIdle", true);
anim.SetBool("RunForwards", false);
StartCoroutine("BackToPatrol");
}
IEnumerator BackToPatrol()
{
isPatrolling = true;
yield return new WaitForSeconds(5);
anim.SetBool("IsIdle", false);
yield return StartCoroutine ("Patrol");
isPatrolling = false;
}
IEnumerator Patrol()
{
Debug.Log("In Patrol");
agent.speed = patrolSpeed;
agent.SetDestination(waypoints[waypointInd].transform.position);
anim.SetBool("WalkForwards", true);
while (Vector3.Distance(this.transform.position, waypoints[waypointInd].transform.position) >= 2 && !isPatrolling)
{
yield return null;
}
waypointInd++;
if (waypointInd >= waypoints.Length) waypointInd = 0;
}
/* public void Patrol()
{
Debug.Log("In Patrol");
agent.speed = patrolSpeed;
if (Vector3.Distance(this.transform.position, waypoints[waypointInd].transform.position) >= 2)
{
agent.SetDestination(waypoints[waypointInd].transform.position);
anim.SetBool("IsIdle", false);
anim.SetBool("WalkForwards", false);
}
if (Vector3.Distance(this.transform.position, waypoints[waypointInd].transform.position) <= 2)
{
waypointInd += 1;
if (waypointInd > waypoints.Length)
{
waypointInd = 0;*/
}
You are calling WaitingOnAction on Update every frame, which will set the animator's IsIdle back to true and start a new BackToPatrol coroutine. This should not happen. Try to check if the character has reached it's destination before calling WaitingOnAction again. Something like:
else if (Vector3.Distance(player.position, this.transform.position) > 30 && !isPatrolling)
{
WaitingOnAction();
}
And in your Coroutine:
IEnumerator BackToPatrol()
{
isPatrolling = true;
yield return new WaitForSeconds(5);
anim.SetBool("IsIdle", false);
yield return StartCoroutine("Patrol");
isPatrolling = false;
}
IEnumerator Patrol()
{
Debug.Log("In Patrol");
agent.speed = patrolSpeed;
agent.SetDestination(waypoints[waypointInd].transform.position);
anim.SetBool("WalkForwards", true);
agent.isStopped = false;
while (Vector3.Distance(this.transform.position, waypoints[waypointInd].transform.position) >= 2 && isPatrolling)
{
yield return null;
}
agent.isStopped = true;
anim.SetBool("WalkForwards", false);
waypointInd++;
if(waypointInd >= waypoints.Length) waypointInd = 0;
}
I didn't test it, but something like this should work.
when I instsiate the bomb it makes more then one sometimes up to 3bombs at once I want it to make 1 bomb not 2 or 3 bombs.
I need a way to be sure it only use the void dropbomb once.
I'm looking forward to your help I like to say sry for the bad English and maby that point that I could have missed something important in my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaneBombDroper : MonoBehaviour
{
public GameObject bomb;
public GameObject bombDropPostion;
public GameObject planePostion;
int bombDropRandomNum;
public float[] dropPostionsX;
bool bombIsDroped;
// Use this for initialization
void Start()
{
bombDropRandomNum = Random.Range(1, 3);
}
void Update()
{
if (bombDropRandomNum == 1 && bombIsDroped != true)
{
if (planePostion.transform.position.x < -2.75f && planePostion.transform.position.x > -3)
{
dropBomb();
}
}
if (bombDropRandomNum == 2&& bombIsDroped != true)
{
if (planePostion.transform.position.x < -9.5 && planePostion.transform.position.x > -10)
{
StartCoroutine("WaitForSeconds");
StopCoroutine("WaitForSeconds");
}
}
}
void dropBomb()
{
Instantiate(bomb, gameObject.transform.position, gameObject.transform.rotation);
}
IEnumerator WaitForSeconds()
{
dropBomb();
yield return new WaitForSeconds(1);
}
}
the bombdrop function fires off a new bomb irrelevant of if there is a bomb already in action - you need to add a condition that if a bomb is firing not to run that new bomb code. You already have the bombisdroped variable - it makes sense that if (!bombisdroped) is then your new bombdrop function
Simply add a flag on your update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaneBombDroper : MonoBehaviour
{
public GameObject bomb;
public GameObject bombDropPostion;
public GameObject planePostion;
int bombDropRandomNum;
public float[] dropPostionsX;
bool bombIsDroped;
private bool launchingBomb = false;
// Use this for initialization
void Start()
{
bombDropRandomNum = Random.Range(1, 3);
}
void Update()
{
if (!launchingBomb)
{
if (bombDropRandomNum == 1 && bombIsDroped != true)
{
if (planePostion.transform.position.x < -2.75f && planePostion.transform.position.x > -3)
{
dropBomb();
}
}
if (bombDropRandomNum == 2&& bombIsDroped != true)
{
if (planePostion.transform.position.x < -9.5 && planePostion.transform.position.x > -10)
{
StartCoroutine("WaitForSeconds");
StopCoroutine("WaitForSeconds");
}
}
}
void dropBomb()
{
launchingBomb = true;
Instantiate(bomb, gameObject.transform.position, gameObject.transform.rotation);
launchingBomb = false;
}
IEnumerator WaitForSeconds()
{
launchingBomb = true;
dropBomb();
yield return new WaitForSeconds(1);
}
}
So I was wondering why this happens... https://gyazo.com/51e7951c85992d7f8851462e59da65da Gif should make clear what's wrong.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GrowlitheShieldSpell : MonoBehaviour {
public GameObject Shield;
public float coolDown = 10;
public float coolDownTimer;
public float EffectcoolDown = 5;
public float EffectcoolDownTimer;
public bool ShieldActive;
GameObject ShieldClone;
public GameObject Growlithe;
public GameObject BuffEffectcoolDowngo;
public Text BuffEffectcoolDownText;
public GameObject ShieldBuffIcon;
void Start(){
ShieldActive = false;
}
void Update () {
if (coolDownTimer < 0) {
coolDownTimer = 0;
}
if (EffectcoolDownTimer < 0) {
EffectcoolDownTimer = 0;
}
if (coolDownTimer > 0) {
coolDownTimer -= Time.deltaTime;
}
if (coolDownTimer == 0){
if (Input.GetKeyDown(KeyCode.Z)){
if (ShieldActive == false){
//when effect starts
ShieldClone = Instantiate(Shield, transform.position, Quaternion.identity)as GameObject;
ShieldClone.SetActive(true);
coolDownTimer = coolDown;
ShieldActive = true;
}}}
//when effect is over
if (EffectcoolDownTimer == 0) {
Shield.SetActive (false);
ShieldActive = false;
EffectcoolDownTimer = EffectcoolDown;
Destroy(ShieldClone);
ShieldBuffIcon.SetActive (false);
}
if (ShieldActive == true) {
EffectcoolDownTimer -= Time.deltaTime;
ShieldClone.transform.position = Growlithe.transform.position;
BuffEffectcoolDownText.text = EffectcoolDownTimer.ToString();
ShieldBuffIcon.SetActive (true);
}
}
}
I hope the cod makes it more clear... It's just very weird that the object gets removed while I never asked for it in any way inside the script. Any help?