On clicking an object drag it, else create new object

I wish to drag an object when clicking on it, but if clicking an empty spot it would instantiate a new object. So far i have two separate scripts for the two actions that work. Now i am not sure how to combine them.

i added this script onto the camera for the instantiation part but got parsing error and Newline in constant.

Thanks for guidance !

Here the script:

using UnityEngine;
using System.Collections;

public class clickAddOrDrag : MonoBehaviour {

private int i;

void Start () {
	
}

void Update()
{
	if (Input.GetMouseButtonDown(0))
	{
		print("Mouse is down");
		
		RaycastHit hitInfo = new RaycastHit();
		bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
		if (hit)
		{	
			//if object hit drag object
			print("Hit " + hitInfo.transform.gameObject.name);
			
		}  
		else 
		{	
			//if not hit create object
			print("No hit");
			
			Vector3 mPos = Input.mousePosition;
			mPos.z = 20.0f; 
			Vector3 pos = Camera.main.ScreenToWorldPoint(mPos);
			GameObject obj = Instantiate(Resources.Load("Prefabs/m”),pos,Quaternion.Euler(90,0,0)) as GameObject;
			obj.gameObject.name = "mon (" + i + ")";
			i++;
			

		}
		
	}
}

}

Seeing the error message you get would help in solving your problem. Also here is a weird character: Load("Prefabs/m”),pos

That character was actually the cause of all error messages. ;) I just copied it over and tested it. See answer below.

KayelGee and CHPedersen, thank you so much! yes i used a wordpad. Lesson learnt! :)

1 Answer

1

Your error occurs because your text editor did something funky with the quotation marks used for the path in Resources.Load. Did you write it in Word or something? The quotation marks are supposed to be this one, both of them —> " <—. Not ", followed by ”, that’s not the same character. :wink:

Fixing that one character resolves the compiler errors:

using UnityEngine; 
using System.Collections;

public class clickAddOrDrag : MonoBehaviour {

private int i;
 
void Start () {
 
}
 
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        print("Mouse is down");
 
        RaycastHit hitInfo = new RaycastHit();
        bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
        if (hit)
        {   
            //if object hit drag object
            print("Hit " + hitInfo.transform.gameObject.name);
 
        }  
        else 
        {   
            //if not hit create object
            print("No hit");
 
            Vector3 mPos = Input.mousePosition;
            mPos.z = 20.0f; 
            Vector3 pos = Camera.main.ScreenToWorldPoint(mPos);
            GameObject obj = Instantiate(Resources.Load("Prefabs/m"),pos,Quaternion.Euler(90,0,0)) as GameObject;
            obj.gameObject.name = "mon (" + i + ")";
            i++;
 
 
        }
 
    }
}
}