How to "press" a button in the inspector tab from script? - c#

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!

Related

Unity Add callbacks to prefab objects dynamically in code

I am creating a canvas with a table containing TextmeshPro Input fields on a row. I'm using the XR Input System for the Oculus Quest Vr Headset and wish to handle input from the controllers so they can interact with the Input fields (Select and DeSelect).
There will be many Rows on this canvas and the number of rows can vary according to the data they look up. So they have to be added dynamically
The input fields are part of a GameObject collection.
I've created a prefab for this collection.
I modified the prefab by placing it in a scene. Assigned to the GameObject the Callback scripts for "On Select" and "On DeSelect" and updated the prefab.
When I check the updated prefab, I see that it has lost the callback references. So I assume they need to be added in code after the GameObject has been instantiated. Can this be done or is this the wrong approach?
Mark
Ok, so I've found a solution to my own question.
I've created a script in the root prefab object.
The child callback then references the root prefab and relevant functions within the prefabs said script.
The code in the root script can pass reference or search for any global gameobjects that need to be aware of the interaction and call their callbacks.
The script is automatically saved along with the prefab and accessible for every instantiation.
Problem solved!

Remove RectTransform from GameObject via Script

I have a GameObject with a RectTransform that I would like to remove via script.
In other words, I want to replace the RectTransform with a regular Transform in the inspector using a script.
In the inspector, you can simply click the RectTransform dropdown and select Remove Component from there and the RectTransform is replaced with Transform. Of course this only works if there are no Components that rely on the RectTransform directly.
If I try this approach with a script like: Destroy(GetComponent<RectTransform>()) I get an error stating:
Can't destroy RectTransform component of
'MyGameObject'. If you want to destroy the game
object, please call 'Destroy' on the game object instead. Destroying
the RectTransform component is not allowed.
Of course, this is somewhat expected, since you can't remove a transform from a gameObject. In the case where I am trying to get back the old Transform component however, this behavior is undesirable.
So my question is: is there a way to replace the current RectTransform with a simple Transform component via script, and how is this done?
You can't delete a conversion.Alternatively, create an empty object and move the entire hierarchy located on that object there. You can simply change the parent of the first child and align the local position, or implement a more complex system, depending on what you need it for.

Unity prefab as an object in inspector asking for attaching object

I am initiating prefabs as objects and then trying to do something using these objects that have those prefabs. However, in the inspector, its asking to attach objects that are actually already attached via code.
Code
public float hitspeed=2f;
public GameObject target, mytarget;
public GameObject arrow,myarrow;
//Use this for initialization
void Start (){
myarrow = Instantiate(arrow, new Vector3(0.02f, -3.98f, 0), transform.rotation);
mytarget = Instantiate(target, new Vector3(-0.06435323f, 2.325303f, 0f), transform.rotation);
}
Inspector
Error
[06:34:34] UnassignedReferenceException: The variable arrow of knife has not been assigned. You probably need to assign the arrow variable of the knife script in the inspector.
[06:34:39] UnassignedReferenceException: The variable myarrow of knife has not been assigned. You probably need to assign the myarrow variable of the knife script in the inspector.
With your object selected so you can see the inspector shown in the image
Go to your Project window, find your prefab.
Drag it to the the inspector where it says "none."
You can also click the little target/circle next to "none" and choose from a list.
It is true that you seem to have assigned myarrow and mytarget, however, you have instantiated them using target and arrow. You have set target using the gui, but not arrow. You must also set arrow.
In general, and to quote from another answer:
[arrow and target have] to be a prefab that you've already created in the Editor and
dragged/dropped onto the Inspector window for this object.
Ensure you:
Created a prefab
Selected this object in the Editor, so the Inspector appears
Drag/dropped that prefab onto the "arrow"/"target" field in the Inspector

Create objects with ground plane detection only once with Vuforia & Unity

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

Instantiate gameobject from a script that is on that gameobject

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.

Categories

Resources