Can't Get Prefab Clone To Follow Mouse
I already looked up questions for the following question, however I am still not getting the results I need. I created the Prefab called "Ground". I then made a script called "PrefabCreation".
Prefab Creation:
using UnityEngine;
using System.Collections;
public class AssetCreation : MonoBehaviour {
public GameObject target;
Vector3 mousePos;
void Start(){
}
void Update(){
mousePos = Input.mousePosition;
mousePos.z = 10f;
target.transform.position = Camera.main.ScreenToWorldPoint(mousePos);
}
}
In order for the Prefab to follow the mouse I need to drag the selected Prefab into the scene, then use the created Prefab's transform as the reference. It works, but not what I needed.
When creating an instance/clone of the Prefab into the game during run time when a key is pressed, I use this code:
Transform groundT = (Transform)Instantiate (target, transform.position, transform.rotation);
However, I can't get that current clone to follow the mouse. The code above is in an Update function. I am using C#.
Comment
Answer by malta32 · Mar 30, 2016 at 05:30 AM
Try assigning the Instantiated game object to a variable.
using UnityEngine;
using System.Collections;
public class AssetCreation : MonoBehaviour
{
public GameObject preFab;
public GameObject target;
Vector3 mousePos;
void Start()
{
target = (GameObject)Instantiate(preFab);
}
void Update()
{
mousePos = Input.mousePosition;
mousePos.z = 10f;
target.transform.position = Camera.main.ScreenToWorldPoint(mousePos);
}
}