Cannot disable directional arrows of my previous location - c#

If i am at location 1 and hit it,after the delay of 10 sec arrows to the location 3 generates.
Now I move to location 3, when I hit location 3, Arrows generated by location 2 should turn off.
I tried hard to get my Deactivate previous function working but failed. Can anybody help regarding this?
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public int _currentCheckPoint = 0;
public ArrowObjects _arrowObjectInstance;
public float _checkPointWaiTime = 10;
public float _elappsedTime;
public bool GenerateArrow = false;
void Start()
{
_arrowObjectInstance = GetComponent<ArrowObjects> ();
foreach (var item in _arrowObjectInstance._listArrowGameObject) {
item.SetActive (false);
}
}
void Update()
{
if (_currentCheckPoint != 0 && GenerateArrow) {
GenerateArrow = false;
Invoke ("DelayedActive", 10f);
}
print (_currentCheckPoint);
}
void DelayedActive()
{
_arrowObjectInstance._listArrowGameObject [_currentCheckPoint - 1].SetActive (true);
}
void DeactivePrevious()
{
_arrowObjectInstance._listArrowGameObject [_currentCheckPoint - 1].SetActive (false);
}
}

Changed the update part from the above script to this.
void Update()
{
if (_currentCheckPoint != 0 && GenerateArrow) {
GenerateArrow = false;
if (_currentCheckPoint > 1) {
_arrowObjectInstance._listArrowGameObject [_currentCheckPoint - 2].SetActive (false);
}
Invoke ("DelayedActive", 10f);
}
and added a check in

Related

Object don't exclude from list

Me need exclude object from the list, i make it as other variants, but it don't work? Why?
I make destroy block as minecraft, but i can see just no thing =/ and i make as can doing.
Code:
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
public class GetTarget : MonoBehaviour
{
[Header("Координаты блока")] // positions blocks
public int positionX;
public int positionY;
public int positionZ;
[Header("Получение цели")] // get target
public static List<GameObject> target = new List<GameObject>();
private void OnTriggerStay(Collider collider) // check on touch to trigger
{
if(collider.gameObject.name == "WorldMap") { return; }
else if(collider.gameObject.name == "Water") { return; }
else if(collider.gameObject.name == "Berries") { return; } // this details in the code don't work now.
else
{
target.Insert(0, collider.gameObject);
Debug.Log("Вы получили " + target[0]); // Вы получите = You can have target[0] now
}
}
private void Update() // set round position
{
Vector3 positions = transform.position;
positionX = (int)Mathf.Round(gameObject.transform.position.x);
positionY = (int)Mathf.Round(gameObject.transform.position.y);
positionZ = (int)Mathf.Round(gameObject.transform.position.z);
positions.x = positionX;
positions.y = positionY;
positions.z = positionZ;
}
}
Thank you to everyone!

Unity 2d dropping more then 1 bomb

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

Countdown starting at random negative number

My countdown timer in ShowRestartDialog() is acting funky. Instead of starting at the defined countdownLength (which is set to 5) it is starting at a random negative number and going down from there. Why would that be happening? Thanks!
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CountdownTimer : MonoBehaviour
{
public static CountdownTimer countdownTimerInstance = null; // Create Singleton
public Object startingScene;
public GameObject timeOutWarningDialog;
private GameObject timerDialogBoxInstance;
private GameObject canvas;
private IEnumerator counter;
private Button stopCountButton;
private Text timerTextField;
public float countdownLength;
public float countdownDelay;
private float countdownInterval = 1.0f;
void Awake()
{
if (countdownTimerInstance == null)
countdownTimerInstance = this;
else if (countdownTimerInstance != null)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public void StartPreCountTimer()
{
GameManager.preCountActive = true;
Debug.Log("StartPreCountTimer Timer has Started!");
if (GameManager.restartWarningActive == false)
Invoke("ShowRestartDialog", countdownDelay);
}
public void RestartPreCountTimer()
{
GameManager.preCountActive = false;
Debug.Log("StartPreCountTimer Timer has Restarted!");
CancelInvoke("ShowRestartDialog");
}
void ShowRestartDialog()
{
GameManager.preCountActive = false;
canvas = GameObject.FindGameObjectWithTag("Canvas");
timerDialogBoxInstance = Instantiate(timeOutWarningDialog); // instantiate timeout warning dialog
timerDialogBoxInstance.transform.SetParent(canvas.transform, false);
timerDialogBoxInstance.SetActive(true);
Text[] textFields = timerDialogBoxInstance.GetComponentsInChildren<Text>(true); // get reference to timer textfields
timerTextField = textFields[2]; // access and assign countdown textfield
stopCountButton = timerDialogBoxInstance.GetComponentInChildren<Button>(); // get reference to keep playing button
stopCountButton.onClick.AddListener(StopDialogTimer); // add button listener
if (timerDialogBoxInstance.activeInHierarchy == true)
InvokeRepeating("StartDialogTimer", 0, countdownInterval);
}
void StartDialogTimer()
{
float s = countdownLength--;
Debug.Log(s);
if (timerTextField != null)
timerTextField.text = s.ToString();
if (s == -1)
{
RestartGame();
}
}
void StopDialogTimer()
{
Debug.Log("Restart Cancelled");
CancelInvoke("StartDialogTimer");
Destroy(timerDialogBoxInstance);
}
void RestartGame()
{
SceneManager.LoadScene(startingScene.name);
}
}
You initialize bad your s variable.
float s = countdownLength--;
On declaration s = 0.0f - 5 ===> -5 first value
You never reach the -1 value to restart your game.
A way to reach is changing this:
if (s <= -1)
{
RestartGame();
}

Unity Character movement issue

I'm new to Unity, I'm using it to make 2D games for Android, when I hold the right button or left button, it doesn't continue moving , it just moves once, What I want to do is when I hold the right button or left button, I want the character to continue moving until I release the button. Could someone please help? I would greatly appreciate it! The tutorial is here
Here's the code for botonDerScript.cs:
using UnityEngine;
using System.Collections;
public class botonDerScript : MonoBehaviour {
private PersonajeScript personaje;
private CircleCollider2D presionar;
void Start()
{
presionar = this.gameObject.GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
tocandoPantalla();
}
private void tocandoPantalla()
{
int numPresiones = 0;
foreach (Touch toque in Input.touches)
{
if (toque.phase != TouchPhase.Ended && toque.phase != TouchPhase.Canceled)
numPresiones++;
}
if (numPresiones > 0 | Input.GetMouseButtonDown(0))
{
Vector3 posicionTap = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 posicionTap2D = new Vector2(posicionTap.x, posicionTap.y);
bool presiono = presionar.OverlapPoint(posicionTap2D);
if (presiono)
{
personaje = this.transform.parent.gameObject.GetComponent<PersonajeScript>();
personaje.MoverJugadorDerecha();
}
}
}
}
Here's the code for botonIzqScript.cs:
using UnityEngine;
using System.Collections;
public class botonIzqScript : MonoBehaviour {
private PersonajeScript personaje;
private CircleCollider2D presionar;
void Start()
{
presionar = this.gameObject.GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
tocandoPantalla();
}
private void tocandoPantalla()
{
int numPresiones = 0;
foreach (Touch toque in Input.touches)
{
if (toque.phase != TouchPhase.Ended && toque.phase != TouchPhase.Canceled)
numPresiones++;
}
if (numPresiones > 0 | Input.GetMouseButtonDown(0))
{
Vector3 posicionTap = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 posicionTap2D = new Vector2(posicionTap.x, posicionTap.y);
bool presiono = presionar.OverlapPoint(posicionTap2D);
if (presiono)
{
personaje = this.transform.parent.gameObject.GetComponent<PersonajeScript>();
personaje.MoverJugadorIzquierda();
}
}
}
}
Here's the code for PersonajeScript.cs :
using UnityEngine;
using System.Collections;
public class PersonajeScript : MonoBehaviour {
private JugadorScript[] jugadores;
void Start () {
jugadores = GetComponentsInChildren<JugadorScript>();
}
// Update is called once per frame
void Update () {
}
public void MoverJugadorIzquierda()
{
foreach (JugadorScript jugador in jugadores)
if (jugador != null) {
jugador.moverIzquierda();
}
}
public void MoverJugadorDerecha()
{
foreach (JugadorScript jugador in jugadores)
if (jugador != null) {
jugador.moverDerecha();
}
}
}
And finally, here's the code for JugadorScript.cs:
using UnityEngine;
using System.Collections;
public class JugadorScript : MonoBehaviour
{
public float velocidad = -10f;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void moverIzquierda()
{
transform.Translate(Vector2.right * velocidad * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}
public void moverDerecha()
{
transform.Translate(Vector2.right * velocidad * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}
}
In your botonIzqScript.cs you have the if statement
if (numPresiones > 0 | Input.GetMouseButtonDown(0))
{
...
}
Change the | in the conditional to ||. | is a binary operator. || is the "OR" operator.
Do the same in your botonDerScript.cs script
Update
To stop moving when the mouse button is released, add the following if statement:
if (Input.GetMouseButtonUp(0) || (Input.touchSupported && numPresiones == 0))
{
// stop moving
}

Add extra life HEART texture 2D

I am working on 2D game.
When player collides with BOMBPrefab lose 1 heart (initial 3 heart), if collides 3 times = GameOver.
Thats is the code (works fine for BombPrefab):
using UnityEngine;
using System.Collections;
public class Heart : MonoBehaviour {
public Texture2D[] initialHeart;
private int heart;
private int many;
// Use this for initialization
void Start () {
GetComponent<GUITexture>().texture = initialHeart[0];
heart = initialHeart.Length;
}
// Update is called once per frame
void Update () {}
public bool TakeHeart()
{
if (heart < 0) {
return false;
}
if (many < (heart - 1)) {
many += 1;
GetComponent<GUITexture> ().texture = initialHeart [many];
return true;
} else {
return false;
}
}
}
I have a second HeartPrefab, I want to check when player collides... IF I have 3 hearts do nothing, IF have 1 or 2 hearts ADD extra heart.
BombPrefab Scrip:
using UnityEngine;
using System.Collections;
public class Bomb : MonoBehaviour
{
public AudioClip clipBomba;
private Heart heart;
private Gerenciador gerenciador;
void Awake ()
{
}
// Use this for initialization
void Start ()
{
gerenciador = FindObjectOfType (typeof(Gerenciador)) as Gerenciador;
}
// Update is called once per frame
void Update ()
{
}
void OnCollisionEnter2D (Collision2D colisor)
{
if (colisor.gameObject.tag == "floor") {
Destroy (gameObject, 2f);
} else {
if (colisor.gameObject.tag == "Bee") {
Som();
heart= GameObject.FindGameObjectWithTag ("Heart").GetComponent<Vidas> () as Vidas;
if (heart.TakeHeart ()) {
Destroy (gameObject);
} else {
gerenciador.GameOver ("GameOver");
}
}
}
}
void Som()
{
GetComponent<AudioSource> ().clip = clipBomb;
AudioSource.PlayClipAtPoint (clipBomb, transform.position);
}
}
First of all try not use GetComponent<>() in update and functions that are run often. It is better to cache components in Start() method. Using FindGameObjectWith...() is also not very efficient.
I would make it differently, each heart as a separate UI element (Toggle), with two states active and inactive. Then your player should have a list of those hearts and methods that allow to take damage and gain life.
int currentHeartsCount = 3;
int maxHeartsCount = 3;
List<Heart> hearts = new List<Heart>();
public void TakeDamage(int damage) {
ChangeHearts(-damage);
}
public void GainLife(int life) {
ChangeHearts(life);
}
private void ChangeHearts(int amount) {
currentHeartsCount += amount;
if(currentHeartsCount> maxHeartsCount)
currentHeartsCount = maxHeartsCount;
if(currentHeartsCount<=0) {
// call player dead code
}
int i = 1;
foreach(Heart heart in hearts) {
heart.SetHeartActive(i<=currentHeartsCount);
i++;
}
}
This is a simplified solution to give you an idea. It is more robust than yours because you can easily change start heart count, and make things like heart "overcharge". Just add base hearts, set max to desired value, and now you can create some special power ups which increase hearts over the initial limit.

Categories

Resources