- Home /
help for start my project...
I want to make an application in which some squares are generated at random positions and that they are destroyed when the user clicks on it (score increase) ...
How can i realize that? Actually I have a background with a script wich generate the square (prefabs)... I can't make the script that detect when a square is pressed... help me :(
var enemy : GameObject;
var timeDelay = 5;
function Start() {
while (true) {
yield WaitForSeconds(timeDelay);
Instantiate( enemy, Vector3(Random.Range(-4.5,4.5),Random.Range(-8.6,8.6),-0.1), Quaternion.identity );
}
}
Answer by Erestyn · Sep 11, 2014 at 09:13 PM
You'll need something in your update function (something that runs once per frame) that acknowledges the player has clicked on a block, and increment the score by X points. You'd need to declare an int to store the users score.
Unityscript isn't my strong point but your code should look something like this.
function Update() {
if (Input.GetMouseButtonDown(0)) {
enemy.renderer.enabled = false;
playerScore++;
}
}
Notice that I disable the renderer rather than use 'destroy'. Once something is destroyed, it can't be instantiated as it was originally.
Answer by orb · Sep 11, 2014 at 07:59 PM
Attach a script with an OnMouseDown() method to the square objects, where you destroy it, like this:
using UnityEngine;
public class Obliterate : MonoBehaviour
{
void OnMouseDown()
{
Destroy(gameObject, 0.01f);
}
}
Except, he's using "javascript", so the code he wants will be a touch different than the C#.
I'm curious as to why you put a .01 second delay on the destroy call.
Already done, but it doesn't work, but it delete all instance of prefabs...
I have just read in the forum that i have to use raycast but I can't understand how to use it
Here it is in java(unityscript), and the reason he might be putting in a delay is so the object has 0.01 seconds to destroy itself.
#pragma strict
function On$$anonymous$$ouseDown() {
Destroy(gameObject);
}
A brief delay has been recommended when destroying stuff, so I went with that. It's quite possible it can be removed. Translating it to UnityScript shouldn't be hard, and it was only an example.
Prefab or not, it shouldn't be destroying every instance. Exactly how does the project layout look like?
you need to add the script to the enemy prefab not to the one that create enemies.
Also you need to have a collider on the enemy prefab to get the onmousedown work
Your answer
Follow this Question
Related Questions
Check if object is destroyed on level load, if so instantiate prefab? 1 Answer
Active Prefabs 1 Answer
Accessing children of an instance doesn't work every time 1 Answer
how to instantiate object with content prefab and not him self 2 Answers
How do I destroy a Instantiated UI image that is pushed on the Canvas? 2 Answers