I am new to coding and I've been trying to solve this problem.
I want to get the user's input from this input box and write it here. I managed to write this code
This is the first script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SubmitButton : MonoBehaviour
{
object myObject = new Object();
public Button btnClick;
public InputField inputUser;
void Start()
{
btnClick.onClick.AddListener(GetInputOnClickHandler);
}
public void GetInputOnClickHandler()
{
Debug.Log("Input is " + inputUser.text);
inputUser.text = myObject.ToString();
}
}
And this is the second script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class txtScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Text txtMy = GameObject.Find("Canvas/Text").GetComponent<Text>();
txtMy.text = "Test" + ToString(SubmitButton.myObject);
}
// Update is called once per frame
void Update()
{
}
}
As you can see, I tried to acces myObject from SubmitButton but I got this error:
Assets\Scripts\txtScript.cs(12,53): error CS0122: 'SubmitButton.myObject' is inaccessible due to its protection level
I've tried to solve this but I can't manage to do it.
I used static modifiers/Getters & Setters but maybe I was doing something wrong.
It's probably easiest, at least while you're still familiarising yourself with coding, to simplify this down and just use one script which references the text input, submit button and text display.
This can be achieved by adding a line and adjusting a line in your first script SubmitButton, and removing or disabling the second txtScript (as it is not needed).
Declare an additional field for the displayText (this should reference the GameObject shown in your second screenshot)
public Text displayText;
Then on the submit action, directly update the displayText text to match the inputUser text
public void GetInputOnClickHandler()
{
Debug.Log("Input is " + inputUser.text);
displayText.text = inputUser.text;
}
Also derHugo mentions, it is not possible to create or meaningfully use the base Object class directly. Most objects you create & access via script in Unity are Components (e.g. Text, Button, Rigidbody, Renderer, etc.), Monobehaviour scripts which are attached to GameObjects (e.g. these scripts), or regular C# classes and structs which you have written to work in tandem with the former two (this last one being the only type you would usually explicitly instantiate using the new keyword).
Related
I'm trying to make an app in Unity which requires your name and other details. I'm using the legacy Input Field to get the answers from the player which worked, but I can't seem to use the Input in any way other than Debug.Log.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReadInput : MonoBehaviour
{
private string input;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void ReadStringInput(string s)
{
input = s;
Debug.Log(input);
}
}
I used this simple script to get the input but I have no clue how to actually use it in the game. It want it to say, for example, Welcome,(Person's Name/Input) outside of the log and actually into a text object.
If you right click in the hierarchy, under UI you can add a text object. I like to use a free package called Text Mesh Pro, which you can get in the asset store, but you don't need to.
Once you've made your text object, it should appear as a child of a gameobject called the Canvas. The text object should have a text field that you can access from script.
Text mytext;
public void UpdateMyText(string s)
{
mytext.text = s;
}
Here's the documentation
Just drag the text object into the script's mytext field in the inspector, and call that function when you want to update your text.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class wastafel : MonoBehaviour
{
public Text ctText;
public static int iscucitangan;//scoring
public int handwash;
void update()
{
handwash = iscucitangan;
ctText.text = "Sudah cuci tangan :" + handwash;
}
}
I tried this script to display a scoring system I made in unity (I use this video as reference : https://www.youtube.com/watch?v=YKeXyaB41EA). I applied this code to a text UI object in my program like this. This is the CT text object. But when I press play, it came up like this, no change at all.
This is my text setting. Is there something that I miss?
It is caused because of the typo, it should be Update() with a capital U and not update().
I've got a problem with creating coin counter for a game.
Underneath is a part of my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Jump : MonoBehaviour
{
private Text coins_text;
void Start()
{
coins_text = GetComponent<Text>();
}
the problem seems to be in the Update method:
void Update()
{
coins_text.text = coins.ToString();
}
Here is the error:
NullReferenceException: Object reference not set to an instance of an object
Any help is appreciated.
Jump.Update () (at Assets/Scenes/Jump.cs:34)
Welcome new user,
don't bother using "GetComponent",
instead use
public Text coins_text;
and open your editor and literally drag the "text item" in to that slot
(If you're not familiar with how to do that, check some basic tutes on Unity!)
Next,
if you do use "GetComponent"
add this line of code
if (coins_text == null) { Debug.Log("there's a f'up"); }
coins_text.text = coins.ToString();
it will clearly tell you if the Text item is actually missing!
NEVER EVER set the text in Update. You can't do that.
You should only set it when the integer value of "coins" changes.
There are many ways to do that, but just do it simply. Have a separate function you call, to change the display, when you need to.
I am new to C# and Unity and am having trouble finding a clear answer to my problem.
I am trying to create a simple TextMeshProUGUI text log buffer in a panel. The buffer itself works fine until I try to access it from another class - I believe because I am not creating the reference to the panel correctly.
Here is my code for the TextMeshProUGUI object collector:
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class TextLogControl : MonoBehaviour
{
public TextMeshProUGUI textPrefab; // Unity prefab
public List<TextMeshProUGUI> textItems = new List<TextMeshProUGUI>();
[SerializeField]
public int maxItems = 100;
public void LogText(string newTextString, Color newColor)
{
Instantiate(textPrefab, transform);
textPrefab.text = newTextString;
if (textItems.Count >= maxItems)
{
textItems.RemoveAt(0); // I should probably be destroying something, but that's another question
}
textPrefab.gameObject.SetActive(true);
textItems.Add(textPrefab);
}
// The above function works correctly if I write a test function within this same class
}
Here is the code for the class that is trying to access the LogText() function:
using System;
using UnityEngine;
public class World : MonoBehaviour
{
Color defaultColor = Color.black;
public TextLogControl textLog;
public void Init()
{
// I need to create a reference here somewhere, but nothing I am trying is working
textLog.LogText("Welcome - you made it!", defaultColor);
}
}
I am putting the TextLogControl script on the Unity GameObject that is holding the TMP objects, and that works on its own.
I thought that I was creating a reference to the holder GameObject by dragging it onto my World object in Unity as below, but I am still getting an NRE when I call World.Init(), which means that I'm doing something wrong, but I cannot figure out what.
I thought this would create the reference that is not being created
Edit: The error I'm receiving is
NullReferenceException: Object reference not set to an instance of an object
When trying to run World.Init() - specifically, textLog is null, even though I have got it dragged onto the appropriate spot in Unity (I believe).
As this is so long for comment,
A null reference means that it is trying to access something that doesn't exist. You either forgot to drag something in the editor, or you are a step ahead and have something un-commented that should still be commented. Your code is using something that isn't there. I recommend you to add this piece of code to your files to check either the error is coming from NullRefrence of class or the else code.
TextMeshProUGUIs = textPrefab.GetComponent<TextMeshProUGUI>();
if (TextMeshProUGUIs == null)
{
Debug.LogError("No TextMeshProUGUI component found.");
}
First of all i want to say Sorry for my bad english and bad grammar
i have a problem and that is when i press play in the editor my array i made in my custom editor disapares(also does that when i update the script)!
First i got a script called “ColorChangerSingle” which is the script i declare varibles
using UnityEngine;
public class ColorChangerSingle
{
public GameObject gameObjectToChange;
public Color color;
}
then i have a script called “ColorChanger” which is the script i make a custom inspector for and all it got is a static list of “ColorChangerSingle”
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorChanger : MonoBehaviour {
public static List<ColorChangerSingle> single = new List();
}
and i have the custom inspector script called “CustomChangeColorInspector” which is the custom inspector script.
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(ColorChanger))]
public class CustomColorChangerInspector : Editor
{
public override void OnInspectorGUI()
{
for (int i = 0; i < ColorChanger.single.Count; i++)
{
EditorGUILayout.BeginHorizontal();
ColorChanger.single[i].gameObjectToChange = (GameObject)EditorGUILayout.ObjectField(ColorChanger.single[i].gameObjectToChange, typeof(GameObject));
ColorChanger.single[i].color = EditorGUILayout.ColorField(ColorChanger.single[i].color);
EditorGUILayout.EndHorizontal();
if (ColorChanger.single[i].gameObjectToChange != null)
if (ColorChanger.single[i].gameObjectToChange.GetComponent() != null)
ColorChanger.single[i].gameObjectToChange.GetComponent().material.color = ColorChanger.single[i].color;
}
EditorGUILayout.BeginHorizontal("box");
if (GUILayout.Button("Add To Array"))
{
ColorChanger.single.Add(new ColorChangerSingle());
}
if (GUILayout.Button("Remove Object In Array"))
{
ColorChanger.single.RemoveAt(ColorChanger.single.Count - 1);
}
EditorGUILayout.EndHorizontal();
}
}
when i add arrays in “not play mode” everything works(setting objects / changing the color of them) but when i press play the array gets “reset”, i think it has to do with the “ColorChanger” script where i set the list equal to a new list of ColorChangerSingle :/
any help is greatly appreciated!
Pictures:
https://gyazo.com/167ab826b6d578ec5a66d9d2586479e8
https://gyazo.com/847a063f9885478200c5a504be1dae2a
thanks for your time and have a great day! //Jrp0h
btw i hope the catagory is good and i know i can clean up the code alot but i made this really quick becuse im working on a secret project and did not want to use that code :)
I don't think your problem comes from the public static List<ColorChangerSingle> single = new List(); line.
What I'd recommend is adding [SerializeField] attributes to your single field and [System.Serializable] to your ColorChangerSingle class. Also are you sure your scene is saved before entering Play mode (this is a common mistake I used to do earlier on) ? If not you can add something like this at the end of the OnInspectorGUI() method :
if(GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(m_Target);
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
EDIT : Also you have to give your custom inspector script a reference to the instance of the script you want to edit (think of many of your GameObjects holding a ColorChanger script), when you call ColorChanger.single[i].gameObjectToChange = [...]; your CustomColorChangerInspector inspector script doesn't know which of your GameObject you refer too.
This is why you have to reference it. The way I usually do it for quick custom inspetocrs (there is more than one way to do it, using serialization for example) is :
[CustomEditor(typeof(ColorChanger))]
public class CustomColorChangerInspector : Editor
{
// I like to declare it once for all but you can also call "(ColorChanger)target" each time to refer to the target
private ColorChanger m_Target;
public override void OnInspectorGUI()
{
m_Target = target as ColorChanger;
for (int i = 0; i < ColorChanger.single.Count; i++)
{
EditorGUILayout.BeginHorizontal();
m_Target.single[i].gameObjectToChange = (GameObject)EditorGUILayout.ObjectField(m_Target.single[i].gameObjectToChange, typeof(GameObject));
[...]
}
}
}