Invoke not working Unity - unity3d

Can you tell me what's wrong in this piece of code? It does not call the Invoke function
public class ReazioneBonus : MonoBehaviour {
void OnTriggerEnter(Collider collider){
string nomeBonus;
if(collider.gameObject.name.Contains("Pallina")){
nomeBonus = gameObject.name;
Debug.Log("bonus colpito");
Debug.Log("il nome del bonus è " + nomeBonus);
if(nomeBonus == "PaddleLungo(Clone)"){ //Allunga il paddle per 5 secondi
Debug.Log("attivazione Paddle Lungo");
Destroy(gameObject);
Debug.Log("bonus colpito da " + Pallina.ultimoGiocatoreToccato);
if(Pallina.ultimoGiocatoreToccato.name == "AvversarioRosso" || Pallina.ultimoGiocatoreToccato.name == "AvversarioVerde"){
Debug.Log("giocatore riconosciuto");
AllungaPaddleVerticale();
Invoke ("RipristinaPadVerticale", 5f); //non chiama la funzione
}else if(Pallina.ultimoGiocatoreToccato.name == "AvversarioBlu" || Pallina.ultimoGiocatoreToccato.name == "AvversarioGiallo"){
Debug.Log("giocatore riconosciuto");
AllungaPaddleOrizzontale();
Invoke ("RipristinaPadOrizzontale", 5f); //non chiama la funzione
}
}
}
}
void AllungaPaddleVerticale(){
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(3F, 0, 0);
}
void AllungaPaddleOrizzontale(){
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(0, 0, 3F);
}
void RipristinaPadVerticale(){
Debug.Log("ripristino il paddle");
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(-3F, 0, 0);
}
void RipristinaPadOrizzontale(){
Debug.Log("ripristino il paddle");
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(0, 0, -3F);
}
}

You destroy the gameObject of that monobehavior:
Destroy(gameObject);
How would these methods be invoked if the monobehavior itself is already destroyed?

When you destroy a GameObject all attached MonoBehaviours' active invokes are cancelled. This to prevent bad references.
Simply destroy the GameObject after your invokes are complete:
public class ReazioneBonus : MonoBehaviour {
void OnTriggerEnter(Collider collider){
string nomeBonus;
if(collider.gameObject.name.Contains("Pallina")){
nomeBonus = gameObject.name;
Debug.Log("bonus colpito");
Debug.Log("il nome del bonus è " + nomeBonus);
if(nomeBonus == "PaddleLungo(Clone)"){ //Allunga il paddle per 5 secondi
Debug.Log("attivazione Paddle Lungo");
Debug.Log("bonus colpito da " + Pallina.ultimoGiocatoreToccato);
if(Pallina.ultimoGiocatoreToccato.name == "AvversarioRosso" || Pallina.ultimoGiocatoreToccato.name == "AvversarioVerde"){
Debug.Log("giocatore riconosciuto");
AllungaPaddleVerticale();
Invoke ("RipristinaPadVerticale", 5f); //non chiama la funzione
}else if(Pallina.ultimoGiocatoreToccato.name == "AvversarioBlu" || Pallina.ultimoGiocatoreToccato.name == "AvversarioGiallo"){
Debug.Log("giocatore riconosciuto");
AllungaPaddleOrizzontale();
Invoke ("RipristinaPadOrizzontale", 5f); //non chiama la funzione
}
}
}
}
void AllungaPaddleVerticale(){
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(3F, 0, 0);
}
void AllungaPaddleOrizzontale(){
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(0, 0, 3F);
}
void RipristinaPadVerticale(){
Debug.Log("ripristino il paddle");
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(-3F, 0, 0);
Destroy(gameObject);
}
void RipristinaPadOrizzontale(){
Debug.Log("ripristino il paddle");
Pallina.ultimoGiocatoreToccato.transform.localScale += new Vector3(0, 0, -3F);
Destroy(gameObject);
}
}

Related

Why Can't I instatiate my object in the position that want at unity?

I'm trying instantiate a sphere to use like a bullet. I want that the bullet be align like the image bellow:
the desirable situation
but when I instantiate through interactive way a have a problem, The sphere stay in diferente coordinate completely different of that I instantiated previouslly. look at the image:
the real situation
why does it happen? how can I solve it?
follow the code from Player.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player
{
public string name;
int currentLife;
int maxLife;
int mentalPower;
public GameObject obj3d; // variável de referência ao modelo 3d do player
// métodos
public Player(string nome, int vidaTotal, int forcaMental)
{
name = nome;
maxLife = vidaTotal;
currentLife = maxLife;
mentalPower = forcaMental;
}
public int Atack(ref bool critico)
{
int aux = mentalPower / 2;
int damage = mentalPower + Random.Range(-aux, aux);
int critical = Random.Range(0, 100);
if(critical < 5) // ataque critico
{
critico = true;
damage *= 2;
}
else
{
critico = false;
}
return (damage);
}
public bool UpdateLife(int dano)
{
currentLife -= dano;
if (currentLife < 0)
{
//comando para destruir o objeto
Object.Destroy(obj3d);
return false;
}
else
return true;
}
public int getLife(int tipo)
{
if (tipo == 0)
return currentLife;
else
return maxLife;
}
public string getName(Player player)
{
return player.name;
}
}
from the Battle.cs:
`using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Battle : MonoBehaviour
{
Player[] players;
int status; // -1= game não começou,0 =game rolando, 1= player 1 vencedor , 2 = player 2 venceu.
Vector3[] spawnPoints;
Quaternion[] rotSpawnPoints;
Color[] playerColors;
public GameObject myPrefab;
Text titulo, info, lifePlayer1, lifePlayer2;
// Bullet
public GameObject objBullet;
Vector3 spawBullet;
// Start is called before the first frame update
void Start()
{
players = new Player[2];
status = -1;
spawnPoints = new Vector3[2];
spawnPoints[0] = new Vector3(2.24f, 0.97f, -4.46f);
spawnPoints[1] = new Vector3(-6.13f, 0.8f, 3.79f);
rotSpawnPoints = new Quaternion[2];
rotSpawnPoints[0] = Quaternion.Euler(0.0f, -250.0f, 0.0f);
rotSpawnPoints[1] = Quaternion.Euler(0.0f, -75.0f, 0.0f);
playerColors = new Color[2];
playerColors[0] = Color.blue;
playerColors[1] = Color.red;
titulo = GameObject.Find("Title").GetComponent<Text>();
info = GameObject.Find("Info").GetComponent<Text>();
lifePlayer1 = GameObject.Find("LifePlayer1").GetComponent<Text>();
lifePlayer2 = GameObject.Find("LifePlayer2").GetComponent<Text>();
spawBullet = new Vector3(1.268f, 1.45f, -3.763f);
}
void CreatePlayer(int nPlayer)
{
print("Entrou na Create Player() com arg = " + nPlayer);
players[nPlayer - 1].obj3d = (GameObject)Instantiate(myPrefab, spawnPoints[nPlayer - 1], rotSpawnPoints[nPlayer - 1]);
players[nPlayer - 1].obj3d.name = "Player" + nPlayer;
players[nPlayer - 1].obj3d.GetComponent<MeshRenderer>().material.color = playerColors[nPlayer - 1];
ControlaInterface();
}
void ControlaCritico(bool status)
{
if (status == true)
{
GameObject.Find("Title").GetComponent<Text>().enabled = true;
GameObject.Find("Title").GetComponent<Text>().color = new Color(GameObject.Find("Title").GetComponent<Text>().color.r, GameObject.Find("Title").GetComponent<Text>().color.g,
GameObject.Find("Title").GetComponent<Text>().color.b, 255f);
GameObject.Find("Title").GetComponent<Text>().text = "CRITOU URRUUU!!!!";
}
else
GameObject.Find("Title").GetComponent<Text>().enabled = false;
}
void ControlaInterface()
{
print("entrei na controla inter");
if(players[0] == null)// entra aqui quando aperta F2
{
print("entrou primeiro if");
GameObject.Find("Title").GetComponent<Text>().text = " Aguardando\nPlayer 1 Azul";
lifePlayer2.enabled = true;
lifePlayer2.text = players[1].getLife(0).ToString() + "/" + players[1].getLife(1).ToString();
}
else if(players[1] == null)// entra aqui quando aperta F1
{
print("entrou segundo if");
GameObject.Find("Title").GetComponent<Text>().text = " Aguardando\nPlayer 2 Vemelho";
lifePlayer1.enabled = true;
lifePlayer1.text = players[0].getLife(0).ToString() + "/" + players[0].getLife(1).ToString();
}
else // player 0 e 1 são diferentes de null
{
print("entrou no else");
lifePlayer2.enabled = true;
lifePlayer1.enabled = true;
lifePlayer2.text = players[1].getLife(0).ToString() + "/" + players[0].getLife(1).ToString();
lifePlayer1.text = players[0].getLife(0).ToString() + "/" + players[1].getLife(1).ToString();
GameObject.Find("Title").GetComponent<Text>().enabled = false;
if (status == -1)
status = 0;
}
GameObject objTmp = null;
}
// Update is called once per frame
void Update()
{
if (status == -1)
titulo.color = new Color(titulo.color.r, titulo.color.g, titulo.color.b,Mathf.Sin(Time.time*2.0f +1.0f)/2.0f) ;
if (Input.GetKeyDown(KeyCode.F1)) //criar player 1(Azul)
{
if (players[0] == null)
{
players[0] = new Player("Player 1 Azul", 100, 14);
CreatePlayer(1);
//GameObject.Find("Title").GetComponent<Text>().enabled = false;
}
}
//-4.87f, 0.8f, -4.83f
if(Input.GetKeyDown(KeyCode.F10))// reseta o game
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
if (Input.GetKeyDown(KeyCode.F2)) //criar player 2(vermelho)
{
if (players[1] == null)
{
players[1] = new Player("Player 2 Vermelho", 100, 14);
CreatePlayer(2);
// GameObject.Find("Title").GetComponent<Text>().enabled = false;
}
}
if (Input.GetKeyDown(KeyCode.Alpha1)) // ataque do player 1
{
//if (objTmp == null)
GameObject objTmp = (GameObject)Instantiate(objBullet, new Vector3(-0.52f, 0.4f, 0.57f), Quaternion.Euler(0f, -45f, 0f));
objTmp.transform.parent = players[0].obj3d.transform;
objTmp.transform.localPosition = spawBullet;
}
}
//-4.87f, 0.8f, -4.83f
if (Input.GetKeyDown(KeyCode.Alpha2)) //ataque player 2(vermelho)
{
// if(objTmp == null)
GameObject objTmp = (GameObject)Instantiate(objBullet, new Vector3(-4.5f, 0.3f, 5.514f), Quaternion.Euler(0f, -45f, 0f));
objTmp.transform.parent = players[1].obj3d.transform;
objTmp.transform.localPosition = spawBullet;
}
}
}
`

Trying to add buff to my game

I'm new at programming. I started a Unity3D course at udemy, I already finished the course, but I'm trying to add a buff to my game. What I want is when my player gets that buff, his shot speed inscreases, I tried to do it but im getting this error when I collide with it
NullReferenceException: Object reference not set to an instance of an object
Powerup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Galaxy Shooter/Scripts/Powerup.cs:54)
EDIT
Album With usefull images
Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public bool canTripleShoot = false;
public bool movSpeedBoost = false;
public bool shield = false;
[SerializeField]
private GameObject _laserPrefabs;
[SerializeField]
private GameObject _tripleShootPrefab;
[SerializeField]
private GameObject _shieldGameObject;
[SerializeField]
private GameObject _explosionPrefab;
[SerializeField]
private float _speed = 5.0f;
[SerializeField]
private GameObject[] _engines;
[SerializeField]
private float _fireRate = 0.25f;
private float _canFire = 0.0f;
public int playerHp = 3;
public int _hitcount = 0;
private UIManager _uiManager;
private GameManager _gameManager;
private SpawnManager _spawnManager;
private AudioSource _audioSource;
// Use this for initialization
void Start () {
_audioSource = GetComponent<AudioSource>();
_spawnManager = GameObject.Find("Spawn_Manager").GetComponent<SpawnManager>();
_uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
_gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
transform.position = new Vector3(0, 0, 0);
if(_uiManager != null)
{
_uiManager.UpdateLives(playerHp);
}
if(_spawnManager != null)
{
_spawnManager.StartSpawn();
}
}
// Update is called once per frame
void Update ()
{
Movement();
//ativar ao pressionar espaço ou botão esquerdo do mouse
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0))
{
Shoot();
}
}
//renderização e cooldown dos tiros
private void Shoot()
{
if (Time.time > _canFire)
{
_audioSource.Play();
if (canTripleShoot== true)
{
Instantiate(_tripleShootPrefab, transform.position, Quaternion.identity);
}
else
{
Instantiate(_laserPrefabs, transform.position + new Vector3(0, 0.95f, 0), Quaternion.identity);
}
_canFire = Time.time + _fireRate;
}
}
//calculo de dano
public void Damage()
{
if(shield == true)
{
shield = false;
_shieldGameObject.SetActive(false);
return;
}
_hitcount++;
if(_hitcount == 1)
{
_engines[0].SetActive(true);
}
if(_hitcount == 2)
{
_engines[1].SetActive(true);
}
playerHp--;
_uiManager.UpdateLives(playerHp);
if(playerHp < 1)
{
Instantiate(_explosionPrefab, transform.position, Quaternion.identity);
_gameManager.gameOver = true;
_uiManager.ShowTitleScreen();
Destroy(this.gameObject);
}
}
public void ShieldUp()
{
shield = true;
_shieldGameObject.SetActive(true);
}
//controle da velocidade de movimento e teleporte
private void Movement()
{
float controleHorizontal = Input.GetAxis("Horizontal");
float controleVertical = Input.GetAxis("Vertical");
//velocidade de movimento
if(movSpeedBoost == true)
{
transform.Translate(Vector3.up * _speed * controleVertical * Time.deltaTime * 2.0f);
transform.Translate(Vector3.right * _speed * controleHorizontal * Time.deltaTime * 2.0f);
}else
{
transform.Translate(Vector3.up * _speed * controleVertical * Time.deltaTime);
transform.Translate(Vector3.right * _speed * controleHorizontal * Time.deltaTime);
}
//limita jogar até o centro da tela
if (transform.position.y > 0)
{
transform.position = new Vector3(transform.position.x, 0, 0);
}
//limita jogar até a borda inferior
else if (transform.position.y < -4.2f)
{
transform.position = new Vector3(transform.position.x, -4.2f, 0);
}
//teleporta jogar se sair da tela na horizontal
else if (transform.position.x < -9.45f)
{
transform.position = new Vector3(9.45f, transform.position.y, 0);
}
else if (transform.position.x > 9.45f)
{
transform.position = new Vector3(-9.45f, transform.position.y, 0);
}
}
//duração triple shot
public IEnumerator TripleShotPowerDownRoutine()
{
yield return new WaitForSeconds(5.0f);
canTripleShoot = false;
}
public void TripleShotPowerUpOn()
{
canTripleShoot = true;
StartCoroutine(TripleShotPowerDownRoutine());
}
//duração boost de movimento
public IEnumerator MovSpeedBoostDownRoutine()
{
yield return new WaitForSeconds(5.0f);
movSpeedBoost = false;
}
//ativa boost de movimento e inicia contagem de duração
public void MovSpeedBoost()
{
movSpeedBoost = true;
StartCoroutine(MovSpeedBoostDownRoutine());
}
}
Laser
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Laser : MonoBehaviour {
[SerializeField]
public float _speed = 10.0f;
[SerializeField]
public bool _laserBoost = false;
// Use this for initialization
void Start () {
_laserBoost = false;
if (_laserBoost == true)
{
_speed = 100f;
}
}
// Update is called once per frame
void Update () {
//código gigante e dificil de decifrar ~irony
transform.Translate(Vector3.up * _speed * Time.deltaTime);
if (transform.position.y > 6f)
{
if(transform.parent != null)
{
Destroy(transform.parent.gameObject);
}
Destroy(gameObject);
}
}
public IEnumerator LaserBoostDuration()
{
yield return new WaitForSeconds(10f);
_laserBoost = false;
}
public void LaserBoost()
{
_laserBoost = true;
StartCoroutine(LaserBoostDuration());
}
}
Powerup
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Powerup : MonoBehaviour
{
[SerializeField]
private float _speed = 3.0f;
[SerializeField]
private int powerupID;
[SerializeField]
private AudioClip _clip;
// Update is called once per frame
void Update ()
{
//movimenta o powerup para baixo
transform.Translate(Vector3.down * _speed * Time.deltaTime);
//destroy o power ao sair da tela
if (transform.position.y <-7)
{
Destroy(this.gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
//acessa o player
Player player = other.GetComponent<Player>();
if(player != null)
{
if(powerupID == 0)
{
//ativa tripleshoot
player.TripleShotPowerUpOn();
}
else if(powerupID == 1)
{
//ativa speedboost
player.MovSpeedBoost();
}
else if(powerupID == 2)
{
//ativar shield
player.ShieldUp();
}
else if (powerupID == 3)
{
Laser laser = GameObject.Find("laser").GetComponent<Laser>();
laser.LaserBoost();
}
}
//detroy powerup
AudioSource.PlayClipAtPoint(_clip, transform.position);
Destroy(this.gameObject);
}
}
}
The error is occuring at
laser.LaserBoost();
One of the two:
1) you don't have a object named "laser" in Scene hierarchy;
2) this object exists but doesn't have a component of type Laser attached to it.
Edit: Now that I saw your image, I can confirm it is the case 1) above. You have a Prefab named "laser", but is doesn't exist in the Scene hierarchy. If you want it to come to existence only when needed, you must instantiate the Prefab in scene.
If you want to search for the Prefab by its name, there is a way, but you'll need to have a folder named Resources inside another named Assets... More info here
Instead, I suggest you another approach. First, you will need a reference to your Prefab in some object, depending on the logic of your program. You seem to have a GameManager class, there could be a good place. Add a new field inside there (if it is the case) like this:
[SerializeField]
public Laser laser
// (...)
Then, change the code that generates the error. GameObject.Find tries to find an object that already exists in scene. In your case, you want to instantiate a clone of a Prefab, by passing a reference to it. Something like this:
else if (powerupID == 3)
{
// I don't know for sure how can you access your GameManager in your program. I will suppose your player have a reference to it.
// You shall change the position depending on your game logic
Laser laserClone = (Laser) Instantiate(player.gameManager.laser, player.transform.position, player.transform.rotation);
laserClone.LaserBoost();
}
Now, select the object in Scene that will have the reference (again, I am supposing it is gameManager) to see its inspector, than fill the laser field with a reference to your Prefab that has a Laser component. Just be sure the clone object will be destroyed when it is not needed.
But... To be very honest, I don't think you will get the result you are expecting anyway. If what you want is just faster shoot rate, the way you're trying to do it now seems pretty convoluted to me. Why don't you do it just like the triple shoot you have? Add a flag inside your player, when it is true the fireRate value changes.

Gain points when the player kill an enemy

I want to gain 10 points when the player kill an enemy but I don't get it. I've created a method to add score on my PuntosPistas script in the Player, and just call the method inside of the CheckHealth of the Enemy but it don't sum 10 points in score. Can anybody help me? This is my code:
In the Enemy:
public class v_AIMotor : vCharacter
{
GameObject Player;
void Start ()
{
Player = GameObject.FindGameObjectWithTag("Player");
}
public void CheckHealth()
{
if (currentHealth <= 0 && !isDead)
{
isDead = true;
Player.GetComponent<PuntosPistas>().KillEnemy ();
print("10 points”);
DisableActions();
}
}
}
In the Player:
public class PuntosPistas : MonoBehaviour
{
public int Score;
public Text TextoContador;
void Start ()
{
Score = PlayerPrefs.GetInt("Score");
TextoContador.text = "" + Score;
}
public void KillEnemy()
{
Score = Score + 10;
TextoContador.text = "" + Score;
PlayerPrefs.SetInt("Score",Score);
}
}
Sorry! This is the full code where I call CheckHealth():
#region AI Health
GameObject Player;
void Start ()
{
Player = GameObject.FindGameObjectWithTag("Player");
}
public void CheckHealth()
{
if (currentHealth <= 0 && !isDead)
{
isDead = true;
Player.GetComponent<PuntosPistas> ().KillEnemy ();
DisableActions();
}
}
public void HealthRecovery()
{
if (currentHealth <= 0) return;
if (currentHealthRecoveryDelay > 0)
{
currentHealthRecoveryDelay -= Time.deltaTime;
}
else
{
if (currentHealth > maxHealth)
currentHealth = maxHealth;
if (currentHealth < maxHealth)
currentHealth = Mathf.Lerp(currentHealth, maxHealth, healthRecovery * Time.deltaTime);
}
}
protected void RemoveComponents()
{
if (_capsuleCollider != null) Destroy(_capsuleCollider);
if (_rigidbody != null) Destroy(_rigidbody);
if (animator != null) Destroy(animator);
if (agent != null) Destroy(agent);
var comps = GetComponents<MonoBehaviour>();
foreach (Component comp in comps) Destroy(comp);
}
public override void TakeDamage(Damage damage)
{
if (rolling || currentHealth <= 0) return;
if (canSeeTarget() && !damage.ignoreDefense && !actions && CheckChanceToRoll()) return;
// change to block an attack
StartCoroutine(CheckChanceToBlock(chanceToBlockAttack, 0));
// defend attack behaviour
if (canSeeTarget() && BlockAttack(damage)) return;
// instantiate hit particle
var hitRotation = Quaternion.LookRotation(new Vector3(transform.position.x, damage.hitPosition.y, transform.position.z) - damage.hitPosition);
SendMessage("TriggerHitParticle", new HittEffectInfo(new Vector3(transform.position.x, damage.hitPosition.y, transform.position.z), hitRotation, damage.attackName), SendMessageOptions.DontRequireReceiver);
// apply damage to the health
currentHealth -= damage.value;
currentHealthRecoveryDelay = healthRecoveryDelay;
// apply tag from the character that hit you and start chase
if (!sphereSensor.passiveToDamage && damage.sender != null)
{
target = damage.sender;
currentState = AIStates.Chase;
sphereSensor.SetTagToDetect(damage.sender);
if (meleeManager != null)
meleeManager.SetTagToDetect(damage.sender);
}
// trigger hit sound
if (damage.sender != null)
damage.sender.SendMessage("PlayHitSound", SendMessageOptions.DontRequireReceiver);
// update the HUD display
if (healthSlider != null)
healthSlider.Damage(damage.value);
// trigger the HitReaction when the AI take the damage
var hitReactionConditions = stepUp || climbUp || jumpOver || quickTurn || rolling;
if (animator != null && animator.enabled && !damage.activeRagdoll && !hitReactionConditions)
{
animator.SetInteger("Recoil_ID", damage.recoil_id);
animator.SetTrigger("HitReaction");
}
// turn the ragdoll on if the weapon is checked with 'activeRagdoll'
if (damage.activeRagdoll)
transform.SendMessage("ActivateRagdoll", SendMessageOptions.DontRequireReceiver);
CheckHealth();
}
#endregion
And this is the error in console:
NullReferenceException: Object reference not set to an instance of an object
Invector.v_AIMotor.CheckHealth () (at Assets/Invector-3rdPersonController/Scripts/CharacterAI/v_AIMotor.cs:504)
Invector.v_AIMotor.TakeDamage (.Damage damage) (at Assets/Invector-3rdPersonController/Scripts/CharacterAI/v_AIMotor.cs:582)
UnityEngine.Component:SendMessage(String, Object, SendMessageOptions)
vMeleeManager:OnDamageHit(HitInfo) (at Assets/Invector-3rdPersonController/Scripts/MeleeCombat/vMeleeManager.cs:295)
UnityEngine.Component:SendMessageUpwards(String, Object, SendMessageOptions)
Invector.vHitBox:CheckHitProperties(Collider) (at Assets/Invector-3rdPersonController/Scripts/MeleeCombat/vHitBox.cs:68)
Invector.vHitBox:OnTriggerEnter(Collider) (at Assets/Invector-3rdPersonController/Scripts/MeleeCombat/vHitBox.cs:48)
please investigate on the way you call CheckHealth(), it's not clear from your code.
That code should be work if you call the method properly, try in this way:
public class v_AIMotor : vCharacter{
GameObject Player;
void Start ()
{
Player = GameObject.FindGameObjectWithTag("Player");
}
public void CheckHealth()
{
if (currentHealth <= 0 && !isDead)
{
isDead = true;
Player.GetComponent<PuntosPistas>().KillEnemy ();
print("10 points”);
DisableActions();
}
}
void Update()
{
CheckHealth();
}
}
void update is not the best way for sure, but should be do the job.

Unity | Multitouch with phics2D Collider

I created the sprites with images on my scene and i made work like buttons. All i want is that the all buttons are working simultaneously like multitouch screen. The code below is what i've done from now on. I use the TouchList which have gameobjects. I supposed the TouchList.Count would increase. However, the TouchList.Counts always show (number)1.
I definitely can't touch two gameObjects in same time because the state of first touched gameobject is changed to "Exit". How can i add touched gameObjects in TouchList?
Please let me know how can i fix this code.
void Update () {
if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) {
touchesOld = new GameObject[touchList.Count];
touchList.CopyTo(touchesOld);
touchList.Clear();
Vector2 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit1 = Physics2D.Raycast(pos, Vector2.zero);
//foreach (Touch touch in Input.touches) {
if (hit1.collider != null) {
GameObject recipient = hit1.transform.gameObject;
touchList.Add(recipient);
//Debug.Log ("recipient : " + hit1.transform.gameObject);
Debug.Log ("I'm hitting "+hit1.collider.name);
Debug.Log ("touchList.Count : " + touchList.Count);
//recipient.SendMessage("OnColliderHit",hit1.point,SendMessageOptions.DontRequireReceiver);
if (Input.GetMouseButtonDown(0)) {
recipient.SendMessage("OnTouchDown",hit1.point,SendMessageOptions.DontRequireReceiver);
}
if (Input.GetMouseButtonUp(0)) {
recipient.SendMessage("OnTouchUp",hit1.point,SendMessageOptions.DontRequireReceiver);
}
if (Input.GetMouseButton(0)) {
recipient.SendMessage("OnTouchStay",hit1.point,SendMessageOptions.DontRequireReceiver);
}
}
//}
foreach (GameObject g in touchesOld) {
if (!touchList.Contains(g)) {
g.SendMessage("OnTouchExit",hit1.point,SendMessageOptions.DontRequireReceiver);
}
}
}
}
This is my modified code. It works well.:-)
void Update () {
if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) {
touchesOld = new GameObject[touchList.Count];
touchList.CopyTo(touchesOld);
touchList.Clear();
foreach (Touch touch in Input.touches) {
Debug.Log ("touch.position : " + touch.position.ToString());
Vector2 pos = Camera.main.ScreenToWorldPoint(touch.position);
RaycastHit2D hit1 = Physics2D.Raycast(pos, Vector2.zero);
if (hit1.collider != null) {
GameObject recipient = hit1.transform.gameObject;
touchList.Add(recipient);
//Debug.Log ("recipient : " + hit1.transform.gameObject);
Debug.Log ("I'm hitting "+hit1.collider.name);
Debug.Log ("touchList.Count : " + touchList.Count);
//recipient.SendMessage("OnColliderHit",hit1.point,SendMessageOptions.DontRequireReceiver);
if (Input.GetMouseButtonDown(0)) {
recipient.SendMessage("OnTouchDown",hit1.point,SendMessageOptions.DontRequireReceiver);
}
if (Input.GetMouseButtonUp(0)) {
recipient.SendMessage("OnTouchUp",hit1.point,SendMessageOptions.DontRequireReceiver);
}
if (Input.GetMouseButton(0)) {
recipient.SendMessage("OnTouchStay",hit1.point,SendMessageOptions.DontRequireReceiver);
}
}
}
foreach (GameObject g in touchesOld) {
if (!touchList.Contains(g)) {
g.SendMessage("OnTouchExit",SendMessageOptions.DontRequireReceiver);
}
}
}
}

Unity 2D: My laser script is getting stuck on an if statement and I don't know why

I've been making a laser in my 2D platformer for the past day. I've made the arm follow to cursor perfectly however on the script for the weapon it self doesn't work. Here is my code
using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
public float fireRate = 0;
public float Damage = 10;
public LayerMask whatToHit;
float timeToFire = 0;
Transform firePoint;
// Use this for initialization
void Awake () {
firePoint = transform.FindChild ("FirePoint");
if (firePoint == null) {
Debug.LogError ("No firePoint");
}
}
// Update is called once per frame
void Update () {
if (fireRate == 0) {
if (Input.GetButtonDown ("Fire1")) {
Shoot();
}
}
else {
if (Input.GetButton ("Fire1") && Time.time > timeToFire) {
timeToFire = Time.time + 1/fireRate;
Shoot();
}
}
}
void Shoot () {
Debug.Log ("Works");
Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition-firePointPosition, 100, whatToHit);
Debug.DrawLine (firePointPosition, (mousePosition-firePointPosition)*100, Color.cyan);
Debug.Log ("Works 2");
if (hit.collider != null) {
Debug.Log ("Work 3");
Debug.DrawLine (firePointPosition, hit.point, Color.red);
Debug.Log ("We hit " + hit.collider.name + " and did " + Damage + " damage.");
}
}
}
The if statement in void Shoot isn't working. The first two debug messages in void Shoot show up in the log however the two in the if statement don't and I have no idea why. Can anyone help?