On the Unity Editor, the OnMouseClick()
function is fired but in my executable file it does not work. It is rare for it to fire, but it does not fire when the object is clicked. I have tried to:
The method used:
public void checkHit()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (ammo > 0)
{
money++;
explosion.Play();
health -= dmg;
}
}
}
}
- Set a BoxCollider2D
- Set a BoxCollider
None of these methods have worked so far when opening the game from the executable file.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(AudioSource))]
public class SeAI : MonoBehaviour {
public Image sof;
public Canvas Game;
public Canvas GameOver;
public Canvas WinScreen;
Vector3 canvasMin;
Vector3 canvasMax;
Vector3 randomVec;
System.Random r;
public Text ammoTxt;
public Text moneyTxt;
public Text outOfAmmo;
public Text gunDmg;
public Text seLife;
public Button addDmg;
public AudioSource explosion;
int ammo = 10;
int money = 0;
int dmg = 1;
int health = 250;
void Start()
{
GameOver.enabled = false;
WinScreen.enabled = false;
canvasMin = Game.GetComponent<Collider2D>().bounds.min;
canvasMax = Game.GetComponent<Collider2D>().bounds.max;
randomVec = new Vector3();
r = new System.Random();
}
void updateScore()
{
ammoTxt.text = "AmMo: " + ammo;
moneyTxt.text = "MoNeY: $" + money;
gunDmg.text = "Gun Damage: " + dmg;
se.text = "Se's Health: " + health;
addDmg.GetComponentInChildren<Text>().text = "Add gun damage: $" + (dmg * 2);
}
public void buyAmmo()
{
if (money > 1)
{
ammo += 6;
money -= 2;
}
}
public void addGunDamage()
{
if(money >= (dmg * 2))
{
dmg += 1;
money -= (dmg * 2);
}
}
public void checkHit()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (ammo > 0)
{
money++;
explosion.Play();
health -= dmg;
}
}
}
}
void checkClicks()
{
if (Input.GetMouseButtonUp(0))
{
if (ammo >= 1)
{
--ammo;
}
}
}
void checkGameOver()
{
if((money <= 1) && (ammo == 0))
{
Game.enabled = false;
WinScreen.enabled = false;
GameOver.enabled = true;
}
}
void checkWin()
{
if(health <= 0)
{
Game.enabled = false;
GameOver.enabled = false;
WinScreen.enabled = true;
}
}
public void tryAgain()
{
SceneManager.LoadScene("Game");
}
public void Quit()
{
Application.Quit();
}
void Update ()
{
checkHit();
updateScore();
checkClicks();
checkGameOver();
checkWin();
if(ammo < 1)
{
outOfAmmo.enabled = true;
}
else if(ammo > 0)
{
outOfAmmo.enabled = false;
}
if(r.Next(0, 30) == 15)
{
randomVec.x = r.Next((int)canvasMin.x, (int)canvasMax.x);
randomVec.y = r.Next((int)canvasMin.y, (int)canvasMax.y);
gameObject.transform.position = randomVec;
sof.transform.position = randomVec;
}
}
}