OnMouseOver() and OnMouseExit() - c#

I am trying to instantiate a number of planes to use as my terrain and give them OnMouseOver() to change them to some color and OnMouseExit() to change them back to the original color.
I attached a plane instantiation script to the main camera to generate the plane prefab and a mouse event script to the plane prefab. I get them all instantiated and the events pass to them, but in-game the mouse events are being applied to either long strips of planes, an entire quadrant, or a random single plane not at the location of the mouse cursor.
I made a new material and applied it to the place prior to turning it into a prefab to replace the standard material set upon creation of the plane.
I have started attempting to use the mouse position to apply the color change to the plane at the current mouse position with Physics.CheckSphere, but I don't fully understand how to tell specifically what gameObject is at a specific position.
public class TerrainGeneration : MonoBehaviour {
[SerializeField]
private Transform groundTile;
private Vector3 row;
private int max = 10;
// Use this for initialization
void Start () {
for ( int i = 0; i <= max; i++)
{
for (int x = 0; x <= max; x++) {
row = new Vector3(i, 0, x);
Instantiate(groundTile, row, Quaternion.identity);
}
}
}
}
public class MouseEvents : MonoBehaviour {
private Color isTargeted;
private Color notTargeted;
private MeshRenderer groundTileMeshRenderer;
private Vector3 mousePosition;
private float mouseX;
private float mouseY;
void Start () {
groundTileMeshRenderer = gameObject.GetComponent<MeshRenderer>();
isTargeted = Color.cyan;
notTargeted = groundTileMeshRenderer.material.color;
}
void Update()
{
mouseX = Mathf.RoundToInt(Input.GetAxis("Mouse X"));
mouseY = Mathf.RoundToInt(Input.GetAxis("Mouse Y"));
mousePosition = new Vector3(mouseX, 0, mouseY);
if (Physics.CheckSphere(mousePosition, 1))
{
**//Get the specific gameObject located at the current mouse position
//Set the gameObject as the target for the color change**
}
}
void OnMouseOver()
{
groundTileMeshRenderer.material.color = isTargeted;
}
void OnMouseExit()
{
groundTileMeshRenderer.material.color = notTargeted;
}
}

So, I found out what the answer is thanks to the Unity forums. My error was in the instantiation transform script. Because I was using the plane primitive 3d object I was not accounting for the size of the plane correctly. The following code snippet for instantiation of each row removes the overlapping that was occurring as the planes are too large to simply place at (0,0,0), (0,0,1), (0,0,2) for example.
row = new Vector3(i * 10, 0, x * 10);
Instantiate(groundTile, row, Quaternion.identity);

tag your gameObjects as necessary and then you can identify them.
If you do, then you can use them like so (purely for example):
public virtual void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "planeA")
{
//do something
}
}

Related

Instantiate predefined number of object along a raycast in Unity

I have a raycast that's being rendered every frame based on 2 points, and those 2 points change position each frame.
What I need is a system that doesn't need a direction, or a number of objects, but instead takes in 2 points, and then instantiates or destroys as many objects as necessary to get the instantiated objects from one side to another minus spaceBetweenPoints. If you wanted you could think of it as an Angry Birds Style slingshot HUD, except without gravity, and based on raycasts.
My Script:
public int numOfPoints; // The number of points that are generated (This would need to chnage based one the distance in the end)
public float spaceBetweenPoints; // The spacing between the generated points
private GameObject[] predictionPoints; // The prefab to be gernerated
private Vector2 firstPathStart; // The starting point for the raycast (Changes each frame)
private Vector2 firstPathEnd; // The ending point for the raycast (Changes each frame)
void start()
{
predictionPoints = new GameObject[numOfPoints];
for (int i = 0; i < numOfPoints; i++)
{
predictionPoints[i] = Instantiate(predictionPointPrefab, firePoint.position,
Quaternion.identity);
}
}
void Update
{
Debug.DrawLine(firstPathStart, firstPathEnd, UnityEngine.Color.black);
DrawPredictionDisplay();
}
void DrawPredictionDisplay()
{
for (int i = 0; i < numOfPoints; i++)
{
predictionPoints[i].transform.position = predictionPointPosition(i * spaceBetweenPoints);
}
}
Vector2 predictionPointPosition(float time)
{
Vector2 position = (Vector2)firstPathStart + direction.normalized * 10f * time;
return position;
}
The current system simply takes in a starting position, a direction, and then moves a preset number of objects in that direction based on time. This way of doing it also causes problems because it's endess instead of only going till the end of the raycast: (Pardon my drawing skills)
Blue line = raycast
Black dots = instantiated prefab
Orange dot = raycast orange
Green dot = end of raycast
Notes:
direction is the momentum which I set in the editor, I needed it to put together what I currently have working, but it shouldn't be necessary when running based on points.
If you ask me I would say it is kinda easy if you know little bit of Math trickery. I'm not saying that I'm very good at Math, but once you get it it's kind of easy to pull off next time. Here if I try to explain everything, i won't be able to explain clearly. Take a look as the code below I've commented the whole code so that you can understand easily.
Basically I used a Method called Vector2.Lerp() Liner Interpolation, which means that this method will return value between point1, and point2 based on the value of 3rd argument t which goes from 0 to 1.
public class TestScript : MonoBehaviour
{
public Transform StartPoint;
public Transform EndPoint;
public float spaceBetweenPoints;
[Space]
public Vector2 startPosition;
public Vector2 endPosition;
[Space]
public List<Vector3> points;
private float distance;
private void Update()
{
startPosition = StartPoint.position; //Setting Starting point and Ending point.
endPosition = EndPoint.position;
//Finding the distance between point
distance = Vector2.Distance(startPosition, endPosition);
//Generating the points
GeneratePointsObjects();
Debug.DrawLine(StartPoint.position, EndPoint.position, Color.black);
}
private void OnDrawGizmos()
{
//Drawing the Dummy Gizmo Sphere to see the points
Gizmos.color = Color.black;
foreach (Vector3 p in points)
{
Gizmos.DrawSphere(p, spaceBetweenPoints / 2);
}
}
private void OnValidate()
{
//Validating that the space between two objects is not 0 because that would be Raise an exception "Devide by Zero"
if (spaceBetweenPoints <= 0)
{
spaceBetweenPoints = 0.01f;
}
}
private void GeneratePointsObjects()
{
//Vlearing the list so that we don't iterate over old points
points.Clear();
float numbersOfPoints = distance / spaceBetweenPoints; //Finding numbers of objects to be spawned by dividing "distance" by "spaceBetweenPoints"
float increnment = 1 / numbersOfPoints; //finding the increment for Lerp this will always be between 0 to 1, because Lerp() takes value between 0 to 1;
for (int i = 1; i < numbersOfPoints; i ++)
{
Vector3 v = Vector2.Lerp(startPosition, endPosition, increnment * i); //Find next position using Vector2.Lerp()
points.Add(v);//Add the newlly found position in List so that we can spwan the Object at that position.
}
}
}
Update: Added, How to set prefab on the positions
I just simply Destroyed old objects and Instantiated new Objects. But remember instantiating and Destroying object frequently in your game in unity will eat-up memory on your player's machine. Os I would suggest you to use Object-Pooling. For the reference I'll add a link to tutorial.
private void Update()
{
startPosition = StartPoint.position; //Setting Starting point and Ending point.
endPosition = EndPoint.position;
//Finding the distance between point
distance = Vector2.Distance(startPosition, endPosition);
//Generating the points
GeneratePointsObjects();
//Update: Generating points/dots on all to location;
InstenciatePrefabsOnPositions();
Debug.DrawLine(StartPoint.position, EndPoint.position, Color.black);
}
private void InstenciatePrefabsOnPositions()
{
//Remove all old prefabs/objects/points
for (int i = 0; i < pointParent.childCount; i++)
{
Destroy(pointParent.GetChild(i).gameObject);
}
//Instantiate new Object on the positions calculated in GeneratePointsObjects()
foreach (Vector3 v in points)
{
Transform t = Instantiate(pointPrefab);
t.SetParent(pointParent);
t.localScale = Vector3.one;
t.position = v;
t.gameObject.SetActive(true);
}
}
Hope this helps please see below links for more reference
OBJECT POOLING in Unity
Vector2.Lerp
I hope I understood you right.
First, compute the A to B line, so B minus A.
To get the number of needed objects, divide the line magnitude by the objects' spacing. You could also add the diameter of the prediction point object to avoid overlapping.
Then to get each object position, write (almost) the same for loop.
Here's what I came up with, didn't tested it, let me know if it helps!
public class CustomLineRenderer : MonoBehaviour
{
public float SpaceBetweenPoints;
public GameObject PredictionPointPrefab;
// remove transforms if you need to
public Transform start;
public Transform end;
private List<GameObject> _predictionPoints;
// these are your raycast start & end point, make them public or whatever
private Vector2 _firstPathStart;
private Vector2 _firstPathEnd;
private void Awake()
{
_firstPathStart = start.position;
_firstPathEnd = end.position;
_predictionPoints = new List<GameObject>();
}
private void Update()
{
_firstPathStart = start.position;
_firstPathEnd = end.position;
// using any small value to clamp everything and avoid division by zero
if (SpaceBetweenPoints < 0.001f) SpaceBetweenPoints = 0.001f;
var line = _firstPathEnd - _firstPathStart;
var objectsNumber = Mathf.FloorToInt(line.magnitude / SpaceBetweenPoints);
var direction = line.normalized;
// Update the collection so that the line isn't too short
for (var i = _predictionPoints.Count; i <= objectsNumber; ++i)
_predictionPoints.Add(Instantiate(PredictionPointPrefab));
for (var i = 0; i < objectsNumber; ++i)
{
_predictionPoints[i].SetActive(true);
_predictionPoints[i].transform.position = _firstPathStart + direction * (SpaceBetweenPoints * i);
}
// You could destroy objects, but it's better to add them to the pool since you'll use them quite often
for (var i = objectsNumber; i < _predictionPoints.Count; ++i)
_predictionPoints[i].SetActive(false);
}
}

How to interact with objects with ARFoundation?

So the idea is to have a plane and grid placement system in augmented reality with the ability to place and move characters on grids. I already have an example for a mobile device, I have a script that generates grid and a script that allows me to place objects and it works just fine, however, I can't figure out how to use all of the above and if it's possible in AR. For example, I want to detect a plane then instantiate a level and put some objects on it.
Here's the script that is attached to the GridManager and is used to make a grid:
[SerializeField] private float size = 0.05f;
public Vector3 GetNearestPointOnGrid(Vector3 position)
{
position -= transform.position;
int xCount = Mathf.RoundToInt(position.x / size);
int yCount = Mathf.RoundToInt(position.y / size);
int zCount = Mathf.RoundToInt(position.z / size);
Vector3 result = new Vector3(
(float)xCount * size,
(float)yCount * size,
(float)zCount * size);
result += transform.position;
return result;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
for (float x = 0; x < 40; x += size)
{
for (float z = 0; z < 40; z += size)
{
var point = GetNearestPointOnGrid(new Vector3(x, 0f, z));
Gizmos.DrawSphere(point, 0.01f);
}
}
}
and here's the one that's attached to the PlacerManager and used to place objects on the grid:
private Grid grid;
private void Awake()
{
grid = FindObjectOfType<Grid>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
PlaceCubeNear(hitInfo.point);
}
}
}
private void PlaceCubeNear(Vector3 clickPoint)
{
var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = finalPosition;
}
You can use the raycast options to identify different objects
Raycasting and/or colliders are the way to go.
The sample scene in AR Foundation has a script called PlaceOnPlane.cs that shows how you can detect when a user touches the screen. E.g:
if (Input.touchCount == 1) {
if (m_RaycastManager.Raycast(Input.GetTouch(0).position, s_Hits, TrackableType.PlaneWithinPolygon))
{
// Raycast hits are sorted by distance, so the first one
// will be the closest hit.
var hitPose = s_Hits[0].pose;
if (spawnedObject == null)
{
spawnedObject = Instantiate(m_PlacedPrefab, hitPose.position, hitPose.rotation);
}
}
}
This allows you to get the screen touch position and then raycast from it to the real world scene. In this example, a game object is instantiated in that location. For your case, you can instantiated a level if your hit a plane or a plane exist around the hit position.

Unity - Spawn Prefabs (Clone Object) got wrong position

I am trying to spawn prefabs (clone object) AGAIN with random position after it's SetActive(false).
What I want :
After Swimmer Object enter trigger with Prefabs (clone object),
set Prefabs (clone object) to SetActive(false) and then it must spawn in random position.
What I have done :
Swimmer.cs <-- This is make clone abject SetActive(false) when trigger
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "Trash") {
other.gameObject.SetActive (false);
}
}
Trash.cs
public GameObject columnPrefab;
public int columnPoolSize = 5;
public float spawnRate = 3f;
public float columnMin = -1f;
public float columnMax = 3.5f;
private GameObject[] columns;
private int currentColumn = 0;
private Vector2 objectPoolPosition = new Vector2 (-15,-25);
private float spawnXPosition = 10f;
private float timeSinceLastSpawned;
void Start()
{
timeSinceLastSpawned = 0f;
columns = new GameObject[columnPoolSize];
for(int i = 0; i < columnPoolSize; i++)
{
columns [i] = (GameObject)Instantiate (columnPrefab, objectPoolPosition, Quaternion.identity);
}
}
void Update()
{
timeSinceLastSpawned += Time.deltaTime;
if (GameControl.instance.gameOver == false && timeSinceLastSpawned >= spawnRate) {
timeSinceLastSpawned = 0f;
float spawnYPosition = Random.Range (columnMin, columnMax);
// This part what I am using to set it active
columns [currentColumn].SetActive(true);
columns [currentColumn].transform.position = new Vector2 (spawnXPosition, spawnYPosition);
currentColumn++;
if (currentColumn >= columnPoolSize) {
currentColumn = 0;
}
}
}
What I have got :
Prefabs (Clone Object) succeed spawn but on wrong position (float on right)
You can take a look at this image
So, how to SetActive clone object and spawn it for random position? Thanks
There isn't actually a problem, and everything in your game is working like it should.
You have your Scene View scrolled out slightly further than your Game View. You can see that if you look at the green seaweed on the left of your screen. See how your Scene View shows more leaves?
The Scene View is purely for the Unity editor, and you can zoom and scroll around independently of where your camera is in your Game View. If you want to move the camera within your Game View, you have to either change the camera parameters on the Main Camera object in your Hierarchy, or you can update Camera.main through code.

Unity 2017.3: transform.position assign attempt is not valid. Input position is { -infinity, 0,0 }

I've been trying to build a raycast controller for a 2D game, and have followed some tutorial series to help me better understand how this is done. So far everything has been going well, and I've actually followed several tutorials on this topic to completion without issue.
However, while using this current character controller I am getting a slew of errors on play, even with no compiler errors present. I have never seen this error, and have not been able to find a solution online about how to fix it. Basically my character disappears on play (I assume its being moved infinitely to the left).
I get two errors: "transform.position assign attempt is not valid. Input position is { -infinity, 0,0 }," and "Invalid world AABB. Object is too large or too far away from origin."
The error occurs on lines 90:
public void LateUpdate()
{
Move(Velocity * Time.deltaTime);
}
and 126:
characterTransform.Translate(deltaMovement, Space.World);
I have tried a bunch of different things, including changing my character's scale, changing Vector2s to Vector3s, removing Space.World, and calling transform.Translate directly (as opposed to using my characterTransform). Nothing seems to work, and for some reason my camera gives me an error sometimes too, though it is hard to reproduce. If I remove either line of code I get no errors, but obviously my character cannot move.
Screenshot of the errors: https://imgur.com/a/24KIN
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Handles the character movement with raycasts
/// </summary>
public class CharacterController2D : MonoBehaviour {
//Defines the number of rays
private const int totalHorizontalRays = 8;
private const int totalVeritcalRays = 4;
private RaycastOrigins raycastOrigins; //References the RayCastOrigins struct
private const float skinWidth = .02f; //Defines the skin width of the rays, which places the origin point of the rays slightly inside the character's box collider
private static readonly float slopeLimitTanget = Mathf.Tan(75f * Mathf.Deg2Rad);
public LayerMask platformMask; //Defines the layermask that will be used to determine how different layers interact with the character
public ControllerParameters2D defaultParameters; //References the ControllerParameters2D class
public ControllerState2D State { get; private set; } //References the ControllerState2D class
public ControllerParameters2D Parameters { get { return overrideParameters ?? defaultParameters; } } //Returns updated parameters, or default parameters if overrideParameters is null
public Vector2 Velocity { get { return velocity; } } //Defines the character's velocity
public bool CanJump { get { return false; } } //Defines whether or not the character can jump
public bool HandleCollisions { get; set; } //Defines whether or not the character needs to handle collisions (because it is colliding with something)
private Vector2 velocity; //The field for the Velocity property
private BoxCollider2D boxCollider; //References the box collider on the character
private ControllerParameters2D overrideParameters; //References the updated parameters (that is, the updated parameters, not the default ones)
private Transform characterTransform; //References the character's transform
private Vector3 localScale; //References the character's scale
//The distance between raycasts
private float horizontalDistanceBetweenRays;
private float verticalDistanceBetweenRays;
private struct RaycastOrigins //Stores the value types that define where the raycasts are created on the box collider
{
public Vector2 topLeft, topRight; //Creates variables to define the upper position of the raycasts
public Vector2 bottomLeft, bottomRight; //Creates variables to define the lower position of the raycasts
}
public void Awake()
{
State = new ControllerState2D(); //Accesses the ControllerState2D script
boxCollider = GetComponent<BoxCollider2D>(); //Accesses the character's box collider
characterTransform = transform; //Accesses the character's transform
localScale = transform.localScale; //Accesses the character's scale
//Gets the ray spacing
horizontalDistanceBetweenRays = CalculateHorizontalRaySpacing();
verticalDistanceBetweenRays = CalculateVerticalRaySpacing();
}
public void Start()
{
}
public void AddForce(Vector2 force)
{
velocity += force;
}
public void SetForce(Vector2 force)
{
velocity = force;
}
public void SetHorizontalForce(float x)
{
velocity.x = x;
}
public void SetVerticalForce(float y)
{
velocity.y = y;
}
public void Jump()
{
}
public void LateUpdate()
{
Move(Velocity * Time.deltaTime); //Moves the character per its velocity, scaled by time
}
public void OnTriggerEnter2D(Collider2D other)
{
}
public void OnTriggerExit2D(Collider2D other)
{
}
private void Move(Vector2 deltaMovement)
{
var wasGrounded = State.IsCollidingBelow; //Keeps track of whether or not the character is grounded
State.Reset(); //Resets the state
if (HandleCollisions) //If the character should handle collisions
{
HandlePlatforms();
CalculateRaycastOrigins();
if (deltaMovement.y < 0 && wasGrounded) //If the character is moving down, and was previously grounded...
{
ClimbDownSlope(ref deltaMovement);
}
if (Mathf.Abs(deltaMovement.x) > .001f) //If the character is moving left or right...
{
MoveHorizontally(ref deltaMovement);
}
MoveVertically(ref deltaMovement); //Calls the MoveVertically method always, since the character always has the force of gravity enacted on it
}
characterTransform.Translate(deltaMovement, Space.World); //Moves the character after all potential movement scenarios have been accounted for
if (Time.deltaTime > 0)
{
velocity = deltaMovement / Time.deltaTime; //Sets the current velocity equal to the change in movement
}
//Clamps the velocity to the maximum x and y velocity defined in Parameters
velocity.x = Mathf.Min(velocity.x, Parameters.maxVelocity.x);
velocity.y = Mathf.Min(velocity.y, Parameters.maxVelocity.y);
if (State.IsMovingUpSlope) //If the character is moving up a slope...
{
velocity.y = 0;
}
}
private void MoveHorizontally(ref Vector2 deltaMovement)
{
var isGoingRight = deltaMovement.x > 0; //Defines if the character is going right
var rayDistance = Mathf.Abs(deltaMovement.x) + skinWidth; //Defines the distance of the raycasts
var rayDirection = isGoingRight ? Vector2.right : -Vector2.right; //Defines in which direction the rays will shoot, depdending on character direction
var rayOrigin = isGoingRight ? raycastOrigins.bottomRight : raycastOrigins.bottomLeft; //Defines the current ray origin
for (var i = 0; i < totalHorizontalRays; i++) //Loops through each of the 8 horizontal rays
{
var rayVector = new Vector2(rayOrigin.x, rayOrigin.y + (i * verticalDistanceBetweenRays)); //Builds the rays (stacking them up with each ray that is added)
Debug.DrawRay(rayVector, rayDirection * rayDistance, Color.red);
var rayCastHit = Physics2D.Raycast(rayVector, rayDirection, rayDistance, platformMask); //Actually draws the rays
if (!rayCastHit) //If the raycast hits something... (rayCastHit is true)
{
continue;
}
if (i == 0 && ClimbUpSlope(ref deltaMovement, Vector2.Angle(rayCastHit.normal, Vector2.up), isGoingRight)) //If the character is now climbing a slope...
{
break;
}
deltaMovement.x = rayCastHit.point.x - rayVector.x; //Clamps horizontal movement based on ray collision
rayDistance = Mathf.Abs(deltaMovement.x); //Clamps the ray distance based on how far the character is allowed to move (i.e. ensures the rays end at walls)
if (isGoingRight) //If the character is going right...
{
deltaMovement.x -= skinWidth; //Ensures that the character moves with the correct value (otherwise would be able to move slightly more based on skinWidth value)
State.IsCollidingRight = true;
}
else //If the character is going left...
{
deltaMovement.x += skinWidth;
State.IsCollidingLeft = true;
}
if (rayDistance < skinWidth + .0001f) //If a collision gets bugged for some reason...
{
break;
}
}
}
private void MoveVertically(ref Vector2 deltaMovement)
{
}
private void ClimbDownSlope(ref Vector2 deltaMovement)
{
}
private bool ClimbUpSlope(ref Vector2 deltaMovement, float angle, bool isGoingRight)
{
return false;
}
private void HandlePlatforms()
{
}
private float CalculateHorizontalRaySpacing()
{
Bounds bounds = boxCollider.bounds; //Sets the 'bounds' variable equal to the bounds of the box collider on the game object
bounds.Expand(skinWidth * -2); //Enforces the skinWidth variable
return bounds.size.y / (totalHorizontalRays - 1); //Ensures that all rays are spaced evenly on the sides of the box collider
}
private float CalculateVerticalRaySpacing()
{
Bounds bounds = boxCollider.bounds; //Sets the 'bounds' variable equal to the bounds of the box collider on the game object
bounds.Expand(skinWidth * -2); //Enforces the skinWidth variable
return bounds.size.x / (totalVeritcalRays - 1); //Ensures that all rays are spaced evenly on the bottom and top of the box collider
}
private void CalculateRaycastOrigins()
{
Bounds bounds = boxCollider.bounds; //Sets the 'bounds' variable equal to the bounds of the box collider on the game object
bounds.Expand(skinWidth * -2); //Enforces the skinWidth variable
//Creates the starting positions of the raycasts
raycastOrigins.bottomLeft = new Vector2(bounds.min.x, bounds.min.y);
raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y);
raycastOrigins.topLeft = new Vector2(bounds.min.x, bounds.max.y);
raycastOrigins.topRight = new Vector2(bounds.max.x, bounds.max.y);
}
}
After doing some research, it seems this is a bug that can sometimes occur.
Not sure why I didn't try this sooner, but reinstalling Unity fixed all the issues...

How do I assign an on click listener to a game object that is created at runtime in Unity using C#?

I created a Quad. I assigned this script to the Quad that contains an array of Game Objects:
public class ShapeGrid : MonoBehaviour {
public GameObject[] shapes;
void Start(){
GameObject[,] shapeGrid = new GameObject[3,3];
StartCoroutine(UpdateGrid());
}
IEnumerator UpdateGrid(){
while (true) {
SetGrid ();
yield return new WaitForSeconds(2);
}
}
void SetGrid(){
int col = 3, row = 3;
for (int y = 0; y < row; y++) {
for (int x = 0; x < col; x++) {
int shapeId = (int)Random.Range (0, 4.9999f);
GameObject shape = Instantiate (shapes[shapeId]);
Vector3 pos = shapes [shapeId].transform.position;
pos.x = (float)x*3;
pos.y = (float)y*3;
shapes [shapeId].transform.position = pos;
}
}
}
}
I cloned those Game Objects so that they appear on a grid like this:
When the user clicks an object, it should disappear. What I did was place this script on every element in my array of Game Objects:
public class ShapeBehavior : MonoBehaviour {
void Update(){
if(Input.GetMouseButtonDown(0)){
Destroy(this.gameObject);
}
}
}
But what happens is when I click on an object to destroy it, every clone of that object will be destroyed. I want only the specific clone to be destroyed, not everything. How do I do that?
The problem is on your Input call, "Input.GetMouseButtonDown(0)" is true in every script when you click the button on mouse, no matter the position of mouse. Attach any kind of collider to gameObject and set it up and put the script with OnMouseDown() method, look here for more info : http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
You can also use raycasting but that's more advanced way of solving this.
Also replace this.gameObject with just gameObject.

Categories

Resources