- Home /
How to make objects have some sort of "Privacy" between each other with a public variable
This one might be new and harder to figure out, not the best with c# but i try. So, the situation is i have 3 Buttons, each with the same script and that script contains a public var [public GameObject ItemToSpawn;] This allows me to drag and drop a prefab onto the button to select which object i would like to spawn from said button. I could go the long way and make 3 different scripts and 3 different buttons but there are many more objects that i would like to spawn in. Code i have currently:
public GameObject ItemToSpawn;
public float yCoord = 0;
public float zCoord = 0;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit; // raycast things
if (Physics.Raycast(ray, out hit)) // Checks to see if mouse clicked button
{
if (hit.transform.name == "SpawnButton")
{
Instantiate(this.ItemToSpawn, new Vector3(0, yCoord, zCoord),Quaternion.identity); //Spawns in item at users location provided
}
}
}
}
Thanks in advance! (Also this is reupload because posted in wrong location)
edit: Looking at your code, it looks like you are trying to create your own kind of button using an object in the scene named SpawnButton. Is this a UI object or a regular mesh sitting in the scene?
Answer by makransov100 · Dec 25, 2017 at 01:51 PM
I believe your main problem is not in object publicity but rather how you check for a unique button press.
Not sure if this is the best way to approach this but it seems to solve the problem you are describing... You don't have to make a new script for each new object. To make things easier just rename the button prefab to something different than "SpawnButton". This would also make things much cleaner in the Hierarchy.
For Example:
Then use a public string variable inside your script to check if the button your raycast hit is the unique button that you want.
This would be the code: (don't forget to set the button name in inspector)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreatObjOnClick : MonoBehaviour
{
public GameObject ItemToSpawn;
public float yCoord = 0;
public float zCoord = 0;
public string buttonName;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit; // raycast things
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name == buttonName)
{
//Spawns in item at users location provided
Instantiate(this.ItemToSpawn,
new Vector3(0, yCoord, zCoord),
Quaternion.identity);
}
}
}
}
}
Thank you so much i was up all night trying to find workarounds but this should work perfectly!
Your answer
![](https://koobas.hobune.stream/wayback/20220612145205im_/https://answers.unity.com/themes/thub/images/avi.jpg)