Question by
MrWandril · Oct 04, 2015 at 04:21 PM ·
c#gameobject2d game
Spawn from GameObject C#
So I have this code:
{
public Transform prefab;
public GameObject clickHere;
private Transform spawn;
private Rect rect = new Rect(161,227,545,75);
void Update()
{
if (Input.GetMouseButton(0) && spawn != null)
{
var pos = Input.mousePosition;
pos.z = -Camera.main.transform.position.z;
spawn.transform.position = Camera.main.ScreenToWorldPoint(pos);
}
if (Input.GetMouseButtonUp(0))
{
spawn = null;
}
}
void OnGUI()
{
Event e = Event.current;
if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition))
{
var pos = Input.mousePosition;
pos.z = -Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
spawn = Instantiate(prefab, pos, Quaternion.identity) as Transform;
}
GUI.Button (rect, "Button");
}
}
It does this:
1- Click the rectangle (there s a button so I can see where it is, it won t be in the future) 2- prefab spawns 3- While you hold the mouse button, you will drag the object
I wanted to spawn the prefab from a game object so I adjusted the rectangle to it, but I soon realized the rectangle will change it s position for different screen resolutions. So I would like the code to do the same but with the gameObject instead of the rectangle.
Comment