- Home /
How to set a gameobject with a mouse click
Hey so I am an amateur coder in c# and I cannot seem to figure out how to answer this question. Here is the script I am working on so far.
using UnityEngine;
using System.Collections;
public class Attack : MonoBehaviour
{
public bool IsDead;
public bool AddEXP;
public bool CanUpgrade;
public bool EnemyIsDead;
public int EnemyHealth;
public int MyHealth;
public int Damage;
public int EnemyDamage;
public int exp;
public int expToUpgrade;
public int enemyToughness;
public GameObject Enemy; // I want the player to be able to set this gameobject with the click of a mouse. HOW?
public GameObject Me;
void Start()
{
IsDead = false;
EnemyHealth = 10;
MyHealth = 20;
Damage = 1;
EnemyDamage = 1;
}
void Update()
{
if (MyHealth <= 0) {
IsDead = true;
} else if (MyHealth >= 1)
{
IsDead = false;
}
if (EnemyHealth >= 1) {
EnemyIsDead = false;
} else if (EnemyHealth <= 0)
{
EnemyIsDead = true;
}
if (EnemyIsDead == true)
{
Destroy (Enemy.gameObject);
}
if(IsDead == true)
{
Destroy (Me.gameObject);
}
if (exp >= expToUpgrade)
{
exp -= expToUpgrade;
Damage += 5;
enemyToughness += 1;
}
EnemyDamage = enemyToughness * 5;
EnemyHealth = enemyToughness * 10; //Will change if gets out of hand
if(EnemyIsDead == true && AddEXP == true)
{
exp += enemyToughness * 5;
AddEXP = false;
}
}
I just figured out a way to do it by just resetting the enemy health if it clicks another enemy but if anyone else knows anything it would be great for the future!
public GameObject enemy;
On the object that the Player can click to select the enemy attach a script and a collider.
Then in the script on the enemy you want to put something with an On$$anonymous$$ouseDown function.
Answer by nixtwiz · May 29, 2016 at 09:16 PM
Combination of these two docs (I frequently refer back to them, always forget parts for some reason):
http://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
The code you need:
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rayHit;
if (Physics.Raycast(ray, out rayHit, 100.0f)){
if(rayHit.collider.tag == "Enemy")
{
enemy = rayHit.collider.gameObject;
}
}
}
Change the 100.0f to the max distance you want to be able to click enemies. Just put a collider on your enemies and tag them "Enemy" (or change that to whatever). If you don't have the colliders on the parent you could use transform.parent to get to the parent object or something like that.
Your answer
Follow this Question
Related Questions
MouseDown Triggered by Another GameObject 1 Answer
How to set Minimum and Maximum angles on Drag to Rotate Gameobject ?? 0 Answers
Mouse drag with specific angle 1 Answer
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Unity UI - Data Management for GameObjects in ScrollRect/TableViews with Large Data Sets 0 Answers