How can i make it so when i click to spawn a game object, they only spawn if the mouse click is on a specific gameObject?.

I’m making a small 2D/3D side-scrolling game to learn unity, and I cant think how to word this question for Google. And this is probably the best place to ask lol.

to move through the levels the player will have to create platforms by clicking on the background, but I have models acting as level geometry (Decoration ect). I want the function for creating the platforms to check if the mouse if hovering over the background plane object or a model and if it’s a model do nothing, if it’s the background then create the gameObject platform.

Here’s my code for creating the platform:

using UnityEngine;
using System.Collections;

public class PlatformGun : MonoBehaviour

{
public GameObject platform;

void Update()
{
if (Input.GetButtonDown(“Fire1”))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
Instantiate(platform, hitInfo.point, Quaternion.Euler(-90, 0, 90) );

	}
}      

}

alt text

RaycastHit tells you everything you need to know about the object you clicked on. Just use the transform member, and from that gameObject. Now you have the reference you need.

you should give your gameobject a tag and check if your ray hits that game object

void Update() {
 if (Input.GetButtonDown("Fire1")) {
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);     RaycastHit hitInfo; 
   if(Physics.Raycast(ray, out hitInfo)){ 
     if(hitInfo.gameObject.tag=="TheName")
      Instantiate(platform, hitInfo.point, Quaternion.Euler(-90, 0, 90) );
      }
   }
}