I have a script called DialogueController, which is attached to a canvas. I would like to instantiate that canvas from the DialogueController script. Whenever I attempt to do this, all of the public objects that were assigned to the canvas through the Unity editor are set to null (including the canvas itself, which is what I am trying to instantiate).
Is there a simple way to do this? I have an alternative solution, but being able to do this would keep my code slightly more compartmentalized.
You could initialize these variables from the script itself, using the resources folders (and the Resources.Load() method). Something like that:
//The canvas is at the path "Assets/Resources/canvas".
function Start () {
your_canvas = Instantiate(Resources.Load("canvas"));
}
From the comments, it seems like you need an initial "seed" instance of that Canvas which contains your script to instantiate more copies if you need. Part 2 is most common for your needs
The easiest way is to have one instance of said canvas already in the scene. You could have the drawable/visible canvas part "disabled" by unticking the little checkbox in the inspector, and then have it enable itself in a function of a script on the GameObject...
void Start ()
{
thisCanvas = GetComponent<Canvas>();
thisCanvas.enabled = true;
}
of course, another way would just be to instantiate one copy from another script which you already have in the scene - classic case:
Create a BLANK GameObject in your scene (CTRL+Shift+N), [F2] rename it "GameManager" (SOME unity functions still bug out when there are spaces in GameObject names BTW) and then attach a new script called GameManager.
This script is basically just here to make sure the right scenes load, and instantiate certain prefabs, make network connections, set player variables that you haven't done from the editor etc etc
so:
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour
{
public GameObject myObject;
void Start ()
{
Instantiate(myObject, transform.position, transform.rotation);
}
}
now drag+drop your "prefab" which you want to instantiate into the slot on your "GameManager" in the inspector.
Note that it doesn't have to be when the game starts, another example is the GameManager script having a function listening for whenever a login is needed, and at that time - it instantiates your login dialog.
Related
I'm trying to make a list where I can add objects in my scene, later on I'm going to loop through them to determine the closest object to my character and make the character perform certain actions. As soon as I created a list, it won't allow me to add any object to my list or reference it and I don't understand why that's happening. Here's a video to further clarify my issue
List Not working for me
my code for further inquiries
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RobberMechanic : MonoBehaviour
{
public List<GameObject> testing = new List<GameObject>();
// void Start()
// {
// }
// // Update is called once per frame
// void Update()
// {
// }
}
Note: wanted to clarify that my unity version was on 2020.3.1f and now I've tried upgrading to 2020.3.10f and this issue occurs in both versions
what you are trying to do is not possible as you are dragging a gameobject inside your list from the hierarchy onto a prefab in the assets folder. Dragging and dropping works on gameObjects that are already inside the a scene/hierarchy.
To achieve your goal you must either:
Add your Terrorist prefab in the scene. Drag your Sphinx object inside it. The Terrorist prefab will then have the appropriate reference of the gameObject and can be used properly.
Turn your Terrorist object into a scriptable gameObject you can then add all sorts of different properties and will be easier to manage. There are tons of videos and documentation on it as well.
You're trying to add a GameObject from your scene to a list in a Prefab which is not possible, you'll have to drop your prefab into the scene before adding game objects to it or make a Prefab of the object you're trying to add to the list.
I'm currently making a game in Unity and I ran into a problem. Essentially what I'm currently trying to do is load a huge list of objects that I require for future scenes in my Recource folder and load them before any scene including the startup scene has been loaded so that I can essentially randomly choose to load scenes instead of being dependent on the first scene in order to load gameobjects that I will need in later scenes. I found a method online that was supposed to be able to do this. I created a gameobject called main put it into my resources folder and attached the Script bellow to it. Then I attached all the gameobjects that I would need to load before any of my scenes to this gameobject ("Main"):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Main : MonoBehaviour
{
//[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
void Start()
{
GameObject main = Instantiate(Resources.Load("Main")) as GameObject;
var mainObj = Instantiate(main);
mainObj.SetActive(false);
GameObject.DontDestroyOnLoad(main);
MySceneManager.LoadScene(1, this);
}
}
When I then run my game for somereason I get a NullReferenceexception stating: (The Object you want to instantiate is null). Does anyone know how I can solve this problem or even if their is an easier solution to the problem I'm trying to solve?
Thanks in advance
You can create an empty "loading scene". The scene will be purely to instantiate the objects you need and will terminate after it is done. Like a main menue in games.
You can put the scripts in the scene select scene.
I am trying to create an AR app using Unity & Vuforia. I have a 3D model that needs to be spawned when ground plane is detected.But this needs to happen only once.
The way Vuforia work is, it keeps on spawning objects when new plane is detected. So what i need to do is either detect plane only once or spawn the object only once. As i am new to Unity, i need help doing this. Great if someone could tell me what i need to do to achieve this.
Vuforia has updated.Now There is no DeploymentStageOnce script.Inorder to stop duplicating while we touch, we have to turn off Duplicate Stage in Content Positioning Behaviour (Script)Check the Inspector when we click Plane Finder.
In your app you should have a Plane Finder object somewhere with the following properties set by default
The Plane Finder object has a Behaviour component attached that calls a Position Content method if a plane was found. That method belongs to the Content Positioning Behaviour and it makes an instance (Clone) of your Ground Plane Stage. In order to avoid more than one instance you should import the vuforia Deploy Stage Once script located here: https://library.vuforia.com/articles/Solution/ground-plane-guide.html and you should change the Plane Finder Behaviour as the following:
I struggled a long with it, in short we must disable AnchorInputListenerBehaviour after hit.
I attached a new script on PlaneFinder with this code below:
<!-- language-all: c# -->
public void OnInteractiveHitTest(HitTestResult result)
{
var listenerBehaviour = GetComponent<AnchorInputListenerBehaviour>();
if (listenerBehaviour != null)
{
listenerBehaviour.enabled = false;
}
}
I added event on Plane Finder Behavior
That's all, I hope it will be useful.
For Updated Versions:
go to "Advanced" setting and "On Interactive Hit Test" script -> Select "Off" option for the script.
Most of the answers are correct but kind of obsolete, the correct way to do that is by code.
Create for example a gameObject called GameManager and pass the GroundPlaneStage and a prefab of the object you want to spawn to a script attached to that GameManager for example call it GameManagerScript.cs, and create a small function called spawnObjects which does the following:
public class SceneManagerScript : MonoBehaviour {
public GameObject objPrefab;
public GameObject ground;
private int count = 0;
public void spawnObject() {
Instantiate(objPrefab, new Vector3(count, 0, 0), Quaternion.identity, ground.transform);
count += 2;
}
}
then after that go to the PlaneFinder specifically to the PlaneFinderBehaviour.cs component you will have callbacks for OnInteractiveHitTest and OnAutomaticHitTest, in your case you need the OnAutomativeHitTest, click + and add a new callback (the function spawnObject in code above like in the image below)
also when you instantiate the object of your preference via the prefab don't forget to write the proper position updates to prevent the objects from getting added in the same position
also don't forget to make the GroundPlaneStage the parent of the object and realize that the position you are adding in the Instantiate() function is relative to that parent (GroundPlaneStage which is represented in the code above with the variable ground)
Finally don't forget to uncheck Duplicate Stage from the "Content Positioning Behaviour" component in the Plane Finder as shown in the picture below:
I hope that helps
please try the vuforia website for this problem
Introduction to Ground Plane in Unity
In the inspector tab I see public variables, checkboxes and buttons as a part of some complex script.
How can I use C# to "press" a button/checkbox or set a value to a variable in the inspector tab, without finding and calling the corresponding functions inside this script?
So I want just to trigger the same effect which would happen if I would manually press a button in the inspector tab.
public Button myButton;
myButton.onClick.Invoke();
Is this what you're looking for?
Inspector shows you the Components of a game object , if you create an empty GameObject You will see the Transform Component Which you can add a reference To that in your Script on another GameObject like public GameObject nameYouWanted and then a slot will appears in in the inspector of the GameObject that script is attached to that which named nameYouWanted and then you can drop the game object that you created in there.
so far you just created a script on another Gameobject and then created a empty GameObject , in this step you can access the transform Component of Second GameObject by just writing someVariable = nameYouWanted.transform.position in start Or update Function in your Script! JUST LIKE THAT! simple as it is , you can access camera component of mainCamera by writing public Camera mainCamera and then access camera components
JUST KEEP IN MIND THAT:
in case of:
public GameObject varName
public is the variables accessibility level
GameObject is Component type
varName is obvious is the variable name
so here is the tricky part for beginners:
for example i have this components on my Camera
How can I access for example the LensDistortionBlur variables?
or another one i.e. Frost Component ?
ANSWER IS:
You Just have to add a reference to that in Your Script like
public LensDistortionBlur LensDistortionBlurEffect;
this image is related to glitch effect:
you see how monodevelop suggests the components variables to use ???
and then in inspector add the target GameObject in this slot (which contains LensDistortionBlur) , here is the good thing: Just because you specified the LensDistortionBlur as Component type, script just asks from that gameobject the LensDistortionBlur component and dont uses other ones, then Use that inside of any function that you want,
More Important thing in that is Component TYPE which is LensDistortionBlur , Yes you should use the component name that you want to access it , More info is Here
IN YOUR CASE
Those bools and variables you mentioned can be accessed by solution that explained above!
Here's the code I'm having problems with:
public class PlaneBehaviour : MonoBehaviour {
public GameObject ClickSymbol;
public void Update() {
if (Input.GetMouseButtonDown(0)) {
Instantiate(ClickSymbol, Input.mousePosition, Quaternion.identity);
}
}
}
When user clicks the left mouse button, then multiple ClickSymbol's will be instantiated. How to prevent that behavior (create the object only once) ?
As for the PlaneBehaviour script, it's attached to multiple (not
intersecting, not overlapping) objects on a plane
That's what I thought you are doing and wanted to verify this before adding an answer. Joe's answer should work but this is a bad design.
You get the multiple Objects instead of one because the script is attached to multiple Objects.
The proper solution here is to have one script that reads from the Input then call a function or trigger an event in another script if required. Create a new script called InputReader or with similar name then move your if (Input.GetMouseButtonDown(0))... Make that that this new script is only attached to one GameObject. Just attach it to an empty GameObject. That's it.
It will prevent problems such as executing code twice when there is an input event.
Now, let;s say that you want to notify another script attached to another GameObject when key is pressed, you can find that GameObject, get that script that is attached to it then call its function.
GameObject obj = GameObject.Find("YourOtherObjectName");
Script script = obj.GetComponent<Script >();
script.notifyKeyPress();
I attached it to multiple game objects to be able to detect which game
object was clicked
That's not how to detect which GameObject is clicked. Since this is a plane, I assume it is a 3D Object with a 3D collider. See 6.For 3D Object (Mesh Renderer/any 3D Collider) from my other post on how to do this.