I am trying to replace a prefab with another.
I am using Instantiate and Destroy.
I am using Raycast to target the prefab with the mouse.
It works but it instantiates many prefabs instead of just one. And the number of instances that it instantiates varies from 6 instances to 1.
Can someone please help me to find the problem?
C# code:
using UnityEngine;
using System.Collections;
public class Srp_LandPositioner : MonoBehaviour {
// Found Mouse select code here:
// http://answers.unity3d.com/questions/23711/destroy-object-on-mouse-click.html
// Update is called once per frame
void Update()
{
//this if check for the mouse left click
if(Input.GetMouseButtonUp(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//this if checks, a detection of hit in an GameObject with the mouse on screen
if(Physics.Raycast(ray, out hit))
{
Debug.DrawRay (ray.origin, hit.point);
print (hit.collider.gameObject.name);
GameObject newApple = Instantiate(GameObject.Find("Pre_Apple"), hit.collider.gameObject.transform.position, hit.collider.gameObject.transform.rotation) as GameObject;
newApple.name = "Apple " + newGameLand.transform.position.x + ", " + newGameLand.transform.position.z;
Destroy(GameObject.Find(hit.collider.gameObject.name));
}
}
}
}