How to modify UI text via script? - c#

A simple question: I'm trying to modify UI text (TextMeshPro if that makes any difference) via C# script. I am using the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coins : MonoBehaviour
{
public Text coins;
void Start()
{
coins = GetComponent<Text>();
}
void Update()
{
coins.text = "text";
}
}
I've done a similar thing in Unity 2018 (I'm currently using Unity 2020.2) and it worked there.
For some reason it doesn't work here though. I would appreciate any help.

Changing text in TMP is practicly the same, but you need to add "using TMPro;" and also change variable type. The code should look like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Coins : MonoBehaviour
{
public TMP_Text coins;
void Start()
{
coins = GetComponent<TextMeshProUGUI>();
}
void Update()
{
coins.text = "text";
}
}

To modify TextMeshPro components, you have to use TMP_Text class.
public class Coins : MonoBehaviour
{
public TMP_Text coins;
void Start()
{
coins = GetComponent<TMP_Text>();
}
void Update()
{
coins.text = "text"; //or coins.SetText(“text”);
}
}

You need to reference the tmp text component instead of the normal Unity text one:
Instead of GetComponent<Text>(); do GetComponent<TextMeshProUGUI>();
Of course don’t forget:
using TMPro;
on top of your code.

Related

Instantiate scriptableobject with random variables

I just started to work with scriptableobject, and I'm trying to Instantiate / Create Instance of a very basic scriptableobject that got 4 line of arrays.
I'm trying to Instantiate one scriptableobject that I created, that every time he's been created he will randomize his variables
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Character",menuName = "Character Creation/Player Units")]
public class CharStats : ScriptableObject
{
[SerializeField]
public string [] charName;
public string [] charDescription;
public string [] charSin;
public Sprite [] charIcon;
}
The changing I'm doing do inside the inspector for one scriptableobject, and just his inside variables will change every time I create new one. Is it possible to achieve?
Ok so I manage to create something might be not the right way, but after pressing a key ( for now testing) its Instantiate my scriptableobjectwith a random Icon I put on for now. Ill add the 3 scripts, bad names coz it's for testing only, (testing - its script that sitting on empty gameobject with reference to my scriptableobject, testing 2 - its script that sitting on a prefab that I Instantiate with the scriptableobject)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class testing2 : MonoBehaviour
{
//public ScriptableObject person;
public CharStats charSats;
public Sprite sprite2;
private SpriteRenderer spriteRender;
private void Start()
{
spriteRender = GetComponent<SpriteRenderer>();
GetRandomSprite();
}
public Sprite GetRandomSprite()
{
int randomIndex = Random.Range(0, charSats.charIcon.Length);
Debug.Log(charSats.charIcon[randomIndex]);
if (sprite2 == null)
{
sprite2 = charSats.charIcon[randomIndex];
spriteRender.sprite = sprite2;
}
return charSats.charIcon[randomIndex];
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class Testing : MonoBehaviour
{
public GameObject Player;
private void Update()
{
SpawnPlayer();
}
public void SpawnPlayer()
{
if (Input.GetKeyDown(KeyCode.A))
{
GameObject spawnPalyer = Instantiate(Player, new Vector3(Random.Range(-10,10), Random.Range(-10, 10)), Quaternion.identity) as GameObject;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Character",menuName = "Character Creation/Player Units")]
public class CharStats : ScriptableObject
{
[SerializeField]
public string [] charName;
public string [] charDescription;
public string [] charSin;
public Sprite [] charIcon;
}

Transfering data between multiple scenes

I am new to C# and Unity and I tried to implement a volume slider. I can now adjust the volume, but the volume resets every time I try to load a new scene.
Could someone tell me how to transfer the volume to other scenes? I am using Unity 2018.3.14f1 and the code I am using for the volume is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class SetVolume : MonoBehaviour
{
public AudioMixer mixer;
public void SetLevel(float sliderValue)
{
mixer.SetFloat("MusicVol", Mathf.Log10(sliderValue) * 20);
}
}
Save It in PlayerPrefs, Then load it on Start or anywhere you need it.
public class SetVolume : MonoBehaviour
{
public AudioMixer mixer;
void Start()
{
SetLevel(PlayerPrefs.GetFloat("MusicVol"));
}
public void SetLevel(float sliderValue)
{
PlayerPrefs.SetFloat("MusicVol", sliderValue);
mixer.SetFloat("MusicVol", Mathf.Log10(sliderValue) * 20);
}
}

Unity3d:Add a public script via inspector

So I am creating a game, which is a Novel game. I want to add a functionality where my friend can add a new dialogue on a character game object. To do that, I already created a main script that enqueue and dequeue all of what is written on the inspector. Two more scripts, one script is a class for creating a new properties on the inspector where my friend can write, the other script functionality is to patch it on the inspector itself. I decided to add a patcher to customize unity editor to add a button. All what is left is a function to add another class where in my friend can write another character name and sentences.
This is what it looks like on Unity Inspector:
Please Help.
DialogueManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehaviour
{
private Queue<string> sentences;
public Text WrapperName;
public Text WrapperContent;
void Start()
{
sentences = new Queue<string>();
}
public void StartDialogue (Dialogue dialogue)
{
WrapperName.text = dialogue.name;
sentences.Clear();
foreach (string sentence in dialogue.sentences)
{
sentences.Enqueue(sentence);
}
DisplayNextSentence();
}
public void DisplayNextSentence()
{
if(sentences.Count == 0)
{
EndDialogue();
return;
}
string sentence = sentences.Dequeue();
WrapperContent.text = sentence;
}
public void EndDialogue()
{
Debug.Log("dialogue Ended..");
}
}
Dialogue.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Dialogue
{
public string name;
[TextArea(3, 10)]
public string[] sentences;
}
StoryElement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StoryElement : MonoBehaviour
{
public Dialogue dialogue;
public void TriggerDialogue()
{
FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
}
}
elementscriptpatcher.cs
using System.Collections;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(StoryElement))]
public class elementscriptpatcher : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if(GUILayout.Button("Add another script"))
{
// I need to write a function for appending a class Dialogue on Dialogue.cs which was initialized on the StoryElement.
}
}
}
you can use GameObject.AddComponent.
if(GUILayout.Button("Add another script"))
{
gameObject.AddComponent<Dialogue>();
}
EDIT : As #derHugo said in comments, we can't add a class that's base is not Monobehaviour. So you will require an Access Class to access Dialogue.cs.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AccessClass : MonoBehaviour {
public Dialogue mClassObject;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Use Ink for Unity, and author the dialogue as text files.

How to properly make variable Public so it can be accessed by another script?

In Unity I have 2 GameObjects, a sphere and a capsule.
And I have a script attached to each.
Capsule script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CapsuleMesh : MonoBehaviour
{
public Mesh capsuleMesh;
void Awake()
{
capsuleMesh = GetComponent<MeshFilter>().mesh;
Debug.Log(capsuleMesh);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Sphere script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeMesh : MonoBehaviour
{
Mesh mesh;
void Awake()
{
mesh = GetComponent<MeshFilter>().mesh;
Debug.Log(mesh);
}
// Start is called before the first frame update
void Start()
{
mesh = capsuleMesh;
}
// Update is called once per frame
void Update()
{
}
}
The mesh = capsuleMesh here is giving me an error about "the name capsuleMesh does not exist in the current context".
I thought that making capsuleMesh public in the other script would make THIS script be able to access it without issue.
What am I doing wrong?
capsuleMesh is a class variable defined in the CapsuleMesh class. It's not a global variable you can use everywhere. You need a reference to the instance of the CapsuleMesh class to retrieve the mesh stored in the capsuleMesh variable.
I've reworked your both scripts to make them work. I've spotted a flaw in your scripts. I guess ChangeMesh is meant to change the mesh of the gameObject? If so, you need to assign a new value to the meshFilter.mesh. Assigning a new reference to the mesh class variable is not enough (it would be pretty long to explain why)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CapsuleMesh : MonoBehaviour
{
public Mesh Mesh
{
get ; private set;
}
void Awake()
{
Mesh = GetComponent<MeshFilter>().mesh;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeMesh : MonoBehaviour
{
// Drag & drop in the inspector the gameObject holding the `CapsuleMesh` component
public CapsuleMesh CapsuleMesh;
private MeshFilter meshFilter;
void Awake()
{
meshFilter = GetComponent<MeshFilter>();
}
void Start()
{
meshFilter.mesh = CapsuleMesh.Mesh;
}
}

scoreText.text not working in unity

"Score:" is not being displayed on unity ide.i have tried a lot and nothing seems to be working and not getting output as expected.Thankyou.Sorry for bad English.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class uiManager : MonoBehaviour {
public Text scoreText;
int score;
// Use this for initialization
void Start () {
score = 0;
}
void score_view()
{
score = move.score;
Debug.Log("uiManager Score:"+score);
scoreText.text = "Score:"+score;
}
// Update is called once per frame
void Update ()
{
score_view();
}
}
Update is called once per frame, if your GameObject is active, and your script is Enabled.
Moreover, your game should be running.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html
You can check this states with these variables:
this.gameObject.activeSelf
this.enabled

Categories