Unity3D Text not changing after being set in Start() - unity3d

I have a Canvas (World Space Render mode) with a Text and a Button component displayed in a tridimensional space (it's a VR app). The canvas instantiated at runtime using a prefab.
I get a reference to the Text object using:
_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent<Text>();
I want to update the text at run-time using:
void Update()
{
_codeTextLabel.text = _codeText;
}
where _codeText is just a variable I update based on specific events.
The problem is that the Text gets updated only the first time, but if I try to change the variable nothing happens. I have tried several combinations and also the method _codeTextLabel.SetAllDirty() but it doesn't work.
The only way to update the text is to re-instantiate the prefab.

Are you instantiating your prefab before setting the values. If you are storing the _codeTextLabel reference before instantiating then your reference will point to the prefab not the runtime object. I can't see the rest of your code, so I can't say for sure. (I would have asked as a comment, but as I'm new I don't have the reputation to do so)
edit: I did a test to try and recreate your problem. I made the following script and it appears to work as expected. CanvasPrefab is a worldspace canvas with a UnityEngine.UI.Text component attached. (The script is attached on an empty game object in the scene btw)
public class ChangeText : MonoBehaviour
{
public GameObject CanvasPrefab;
private GameObject runtimeCanvas;
public string runtimeText = "something";
private Text textRef;
// Start is called before the first frame update
void Start()
{
runtimeCanvas = GameObject.Instantiate(CanvasPrefab);
textRef = runtimeCanvas.GetComponentInChildren<Text>();
}
// Update is called once per frame
void Update()
{
textRef.text = runtimeText;
}
}

as long as you did something wrong, It works absolutely so I guess there are several cases
Failed to do "_codeTextLabel = canvasPrefab.transform.Find("CodeTextLabel").gameObject.GetComponent();"
'_codeTextLabel' lost reference from 'GameObject.
Doesn't change runtimeText' change at all
Subscription of events failed I mean, your updating scripts doesn't get proper event to update that text.
Without codes, this is only thing I can guess for yours so please check above I hope there is case among above.

Related

How to disable the Tracked Pose Driver in a Unity VR Application?

I need to write a VR application that disables HMD positional tracking for a specific situation and then reenable it again.
In the UI it is a simple as ticking and unticking the TrackedPoseDriver shown in the picture below.
How can I do that via Scripting?
I assume I need to use the enabled property of a game object. But I don't know how to grab a hold of this GameObject (or Component).
EDIT: In case this was clear this is GameObject/Component associated to the main camera.
Ok. So I was able to do It.
What I did is I search MonoBehaviour Based Components on the camera and then cast it to a MonoBehaviour once I found the right one. And then used the enabled property. Like this:
Component[] components = Camera.main.GetComponents(typeof(MonoBehaviour));
bool found = false;
foreach(Component component in components) {
string name = component.ToString();
MonoBehaviour mb = (MonoBehaviour) component;
if (name.Contains(TRACK_POSE_DRIVER_NAME)){
mbTrackingPose = mb;
found = true;
break;
}
}
The unique string that the toString() method provided was somethign like (I don't have it on hand) "Main Camera (Unity.XR.TrackedPoseDriver)". So I just made sure that the string had the "TrackedPoseDriver" and stored that as a MonoBehaviour.
I hope this helps someone else.

How do you fire off the Cinemachine Impulse source without using the Collision one?

How do properly call GenerateImpulse() to implement Cinemachine's camera ImpulseListener (camera shake) via the ImpulseSource? I can get it working if I put a CollisionImpuleSource on the player, but I don't want that. I want to use the Impulse Source and then with code, determine when to shake.
I'm looking at the documentation https://docs.unity3d.com/Packages/com.unity.cinemachine#2.3/manual/CinemachineImpulseSource.html but not seeing how to properly make the ImpulseSource fire off.
I set a private...
public CinemachineVirtualCamera vCamera;
private CinemachineImpulseSource _impulseSource;
I can call the generateImpulse...
_impulseSource.GenerateImpulse();
but I don't see how to get the component
private void Start(){
_impulseSource = vCamera.GetCinemachineComponent<CinemachineImpulseSource>();
}
I get an error..
The type
'Cinemachine.CinemachineImpulseSource'
must be convertible to
'Cinemachine.CinemachineComponentBase'
in order to use it as parameter 'T' in
the generic method 'T
Cinemachine.CinemachineVirtualCamera.GetCinemachineComponent()'
but if I change the private too..
private CinemachineComponentBase _impulseSource;
that doesn't help. Need some guidance on how this should be referenced.
Think of the CinemachineImpulseSource as a component on a custom GameObject.
Attach the CinemachineImpulseSource Script Component to a new gameobject. You could probably add it to the same GO where the script from your question is attached to, did not test this though.
Configure the impulse source component according to your needs and reference it. If its on the same GameObject, create a public field just as with your camera reference and assign it in the inspector or get it using GetComponent<CinemachineImpulseSource>(). Then you can call GenerateImpulse() on it.
public CinemachineVirtualCamera vCamera;
public CinemachineImpulseSource ImpulseSource; // Assign in inspector
...
ImpulseSource.GenerateImpulse();

Best practice to to access components using scripts in Unity?

I am new to Unity so go easy on me. :)
I added an game object with a text field component (via TextMeshProUGUI) to my heads up display in my scene. I want to use this to display various statistics on it for debugging purposes during game play.
I then created a script which I added as a component to the same game object that holds my text component. Is this the best practice? Not sure how else I would get the script to execute.
Once I had my script created, I needed to find the text component as well as some other components in my scene so I could display the debug information. Below you can see how I did it... it feels a little dirty to be searching the entire scene to find these things. Would love some insight on how long-time Unity programmers go about this!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerDebugStatistics:MonoBehaviour {
TextMeshProUGUI playerDebugStatisticsText;
PlayerCharacterController playerCharacterController;
Health playerHealth;
private void Start() {
// First find the object in the scene named "PlayerDebugStatisticsText" and then get it's TextMeshProUGUI component
this.playerDebugStatisticsText = GameObject.Find("PlayerDebugStatisticsText").GetComponent<TextMeshProUGUI>();
// Get the player character controller
this.playerCharacterController = GameObject.FindObjectOfType<PlayerCharacterController>();
// Get the player health from the player character controller
this.playerHealth = playerCharacterController.GetComponent<Health>();
}
void Update() {
// Update the text every frame
this.playerDebugStatisticsText.SetText(string.Format("{0:N2}", this.playerHealth.currentHealth));
}
}
3 ways
Create an inspector reference to the other object and access it from your script - a public or private (with [SerializeField]) attribute in your script - and drag the component in like in this video: https://youtu.be/dMgQOP7kdxg?t=425
Use the singleton pattern: https://www.youtube.com/watch?v=5p2JlI7PV1w
Use dependency injection - https://github.com/modesttree/Zenject
Your way isn't terrible if you don't do it in the Update() loop, and cache your objects (like it appears you are doing), but if you need that performance in Start(), the above options can help.

How do i change an existing text mesh?

I can't figure out how to change an existing text mesh already in my scene. I have tried to use
void changeScore()
{
TextMesh textObject = GameObject.Find ("scoreText").GetComponent<TextMesh> ();
textObject.text = "test";
}
but it doesn't work. I have been trying multiple different methods to no avail.
The code you posted is correct, which means you're either
not calling changeScore()
getting an error message
changing the TextMesh's text later in the frame before it is rendered

SceneManager.LoadScene(string) doesn't recognize scene name

I've seen similar questions all over the internet, but none seem to apply to my situation.
I have a very simple project with two scenes: MainMenuScene and OtherScene. OtherScene is nothing but a blank canvas, and MainMenuScene just has a button which is meant to be used to navigate to OtherScene. The Main Camera has the following script attached to it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LaunchScene : MonoBehaviour {
public void LaunchSceneOnButtonClick(int index)
{
SceneManager.LoadScene(index);
}
public void LaunchSceneOnButtonClick(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
}
and in the OnClick() of the button, this script is called. I have made sure to add both levels to the Build Settings.
If I call the version of the LanchSceneOnButtonClick which takes an integer argument (and specify the appropriate value in the OnClick() method) then the desired scene loads.
However, if I call the version which takes a string argument and use the exact name of the scene I want to load (and I've quadruple checked that it is indeed the exact string, that the string name has no spaces or hidden characters, and have copy pasted the scene name into the OnClick() argument field) the scene does not load and instead I get the error message
Scene "OtherScene" couldn't be loaded because it has not been added to
the build settings or the AssetBundle has not been loaded.
Since using the scene index works, we know it was added to the Build Settings properly, so I reason that there is some issue with the scene name. But I've copied it exactly. I want to avoid using the full path of the scene in case I later decide to move scenes around to different folders, so what are my options here?
Thanks in advance.
EDIT:
Adding screenshots.
Scene in folder structure:
Scenes in build settings:
OnClick() input:
Keep in mind I've also tried the input to OnClick() with and without quotation marks.
The only possible problems are these:
The string passed is different from the scene name; bear in mind, the string used in LoadScene is not case sensitive, i.e. you can use OtherScene, OTHERscene, etc.
The scene in the build settings is not active (i.e. with the checkmark on the left disabled).
The scene isn't present at all in the build settings.
The full path of the scene is irrelevant btw, you can have OtherScene inside any dir/subdir in the Assets, and you'll need only the name of the scene. You need the full path of the scene only if you have more than scene with the same name in different paths (and anyway you shouldn't, it's such an obvious terrible practice).
EDIT: You say that you tried even without " (as you should do, when entering string fields in the inspector you don't need them), what happens if you modify the method body to:
public void LaunchSceneOnButtonClick(string sceneName)
{
SceneManager.LoadScene("OtherScene");
}
Try this and report back what happens please.
I had also the problem that
public void loadScene(string scene)
{
SceneManager.LoadScene(scene);
}
did not work for me in the first place. What did I do? I'm saving the names of my scenes in a List (read from a file) and from that List I choose the scene I need.
But somehow the reading progress seems to give me some unwanted characters so the scene loading does not work as intended. When I added .Trim() it started to work.
For a better understanding, here's an example:
string s = sceneList[1].Trim();
this.loadScene(s);
public void loadScene(string scene)
{
SceneManager.LoadScene(scene);
}
So make sure that you get rid of unwanted characters.