- error message
After completing the bullet script operation, I tried to insert the script into Bullet Sprite in 2D Object format, but an error was displayed and the insertion was not possible. I tried turning off and on the editor because I thought it was a bug because I had the same file name and class name, but it didn't work. Do you happen to know about this problem? The editor version is 2021.3.11f1.
Bullet Script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class Bullet : MonoBehaviour
{
[SerializeField]
private float speed = 10f;
private IObjectPool<Bullet> pool;
void Update()
{
transform.Translate(Vector2.up);
}
public void SetPool(IObjectPool<Bullet> bulletPool)
{
Launcher.Instance.bulletPool = pool;
}
private void OnBecameInvisible()
{
Launcher.Instance.bulletPool.Release(this);
}
}
I turned off and on the editor and changed the class name because I thought it was different.
Related
So I have a 2D platformer parkour game which holds a timer when player starts level. I have 5 levels and at the end of each level, I want to keep the last time value and display them at the end of the game.
So far, I tried to hold the last time value when player triggers the End portal and store them in an array in the code below. Here are the scripts:
Time Data Manager Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class timeDataManager : MonoBehaviour
{
public string[] timeDataArr;
void Start(){
}
void Update(){
Debug.Log(timeDataArr[SceneManager.GetActiveScene().buildIndex-1]);
}
public void AddTimeData(string timeData, int levelBuildIndex){
timeDataArr[levelBuildIndex-1] = timeData.ToString();
}
}
End Portal Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class EndPortal : MonoBehaviour
{
public AudioSource aSrc;
private int sceneNumber;
public GameObject bgAudio;
public Text scoreText;
string textData;
public timeDataManager tDManager;
void Start(){
sceneNumber = SceneManager.GetActiveScene().buildIndex;
tDManager = GameObject.FindGameObjectWithTag("TimeDataManager").GetComponent<timeDataManager>();
}
void OnTriggerEnter2D(Collider2D col){
if (col.gameObject.tag == "Player"){
aSrc.Play();
Destroy(bgAudio);
textData = scoreText.text;
Debug.Log(textData);
Debug.Log(sceneNumber);
tDManager.AddTimeData(textData,sceneNumber);
SceneManager.LoadScene(sceneBuildIndex:sceneNumber+1);
}
}
}
As I said before, I tried to keep all timer values at the end of each level and store them in an array in my timeDataManager script. But it's not working.
Any ideas on how to fix? Or do you have any other ideas? Thanks a lot for your time.
Issylin's answer is a better solution for your needs but i want to mention couple of things about your code.
One thing about your timeDataArr. If you don't touch it in inspector, you need to initialize it first. So let's say, if you want to hold 5 levels of time data, you need to do something like;
public string[] timeDataArr = new string[5];
or
public class timeDataManager : MonoBehaviour
{
public string[] timeDataArr;
public int sceneAmount_TO_HoldTimeData = 5;
void Start()
{
timeDataArr = new string[sceneAmount_TO_HoldTimeData];
}
}
or
public class timeDataManager : MonoBehaviour
{
public string[] timeDataArr;
public int sceneAmount_NOT_ToHoldTimeData = 1;
void Start()
{
timeDataArr = new string[SceneManager.sceneCountInBuildSettings - sceneAmount_NOT_ToHoldTimeData];
}
}
Another thing is you need to be careful about levelBuildIndex-1. If you call that in first scene,
SceneManager.GetActiveScene().buildIndex
will be 0 and levelBuildIndex-1 will be -1 or in Debug part it will be timeDataArr[-1] but array indexes must start with 0. So it will throw an error.
One more thing, this is not an error or problem. Instead of this part
tDManager = GameObject.FindGameObjectWithTag("TimeDataManager").GetComponent<timeDataManager>();
you can do
tDManager = FindObjectOfType<timeDataManager>();
There are several way to achieve what you're trying to do.
The easier would be to use a static class for such a simple data like the one you're carrying through your game.
using System.Collections.Generic;
public class Time_Data
{
/// TODO
/// Add the members
/// e.g. your time format as string or whatever,
/// the scene index, etc
}
public static class Time_Manager
{
private static List<Time_Data> _times;
public static void Add_Time(in Time_Data new_time)
{
_times.Add(new_time);
}
public static List<Time_Data> Get_Times()
{
return _times;
}
public static void Clear_Data()
{
_times.Clear();
}
}
Use it like any other static methods within your OnTriggerEnter2D call.
Time_Manager.Add( /* your new data here */ );
The other way, if you intend to stay with a game object within your scenes, would be to use the DontDestroyOnLoad method from Unity so your game object which has your script timeDataManager would remain.
Note that in your code, using string[] might be unsafe. For your use of it, consider using a List<string>.
How it should work - when i click on the UI button, the score increases and is displayed using text.
How it's working - An error that says 'NullReferenceException: Object reference not set to an instance of an object'
There are two scripts on two different game objects.
Player Script
using UnityEngine;
public class Player : MonoBehaviour
{
ScoreManager scoreManager;
private void Start()
{
scoreManager = new ScoreManager();
}
public void UpdateScore()
{
scoreManager.IncrementScore();
}
}
ScoreManager Script
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
private int score = 0;
public TextMeshProUGUI scoreText;
public void IncrementScore()
{
score++;
scoreText.text = score.ToString();
}
}
When I use Debug.Log(score.ToString()), it displays the score in the console. But when I use textmeshprougui, it gives an error.
Also, I've dragged the text into the inspector, so that cannot be a problem for the null referrance. I've checked it multiple times.
Why am I not able to update the text from another script?
Null reference exception is in your Player.cs script and caused because of the code in your Start() method
ScoreManager scoreManager;
private void Start()
{
scoreManager = new ScoreManager();
}
Remove the code in your Start() method. Because there is a field ScoreManager scoreManager;, you drag the gameobject which has the script ScoreManager.cs into its slot in the Player.cs script. Now you have the reference of the ScoreManager.cs script in your Player.cs script.
Now, you are resetting its reference in your Start() method. This caused the null reference exception.
I am trying to make a FlappyBird on WebGL with Unity. I made scores system, and there is no bug finded while runing on unity editor, but when I build with WebGL, Text don't shows up. Only legacy Text (Not TextMeshPro) causes this problm, so it would be helpful too if there is a way to use TextMeshPro. https://r0k0r.github.io/FlappyBirdWebGL is my game link, and https://github.com/R0K0R/FlappyBirdWebGL is my github link. I don't know this will help, but I am currently coding with ubuntu.
this is my Score.cs code that returns current score:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public static int score = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(){
score++;
}
public static int returnScore(){return score;}
}
and this is my ApplyScore.cs code that applys score to text gameobject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ApplyScore : MonoBehaviour
{
public Text ScoreText;
// Start is called before the first frame update
void Start()
{
ScoreText.text = "0";
}
// Update is called once per frame
void Update()
{
ScoreText.text = Score.returnScore().ToString();
}
}
this is what it looks like
and this is what it should look like
I've recently discovered the URP and am developing a 2D game for fun. I added a global 2d light and set up some code to grab the light component, but unity keeps saying that light 2D does not exist. The error in unity is "error CS0246: The type or namespace name 'Light2D' could not be found". This is the code I have so far. I also followed a tutorial by Jimmy Vegas to grab the system time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class DayNight : MonoBehaviour
{
public GameObject theDisplay;
public GameObject GL;
public int hour;
public int minutes;
public int totaltime;
private bool AM;
void Start()
{
totaltime = System.DateTime.Now.Hour;
hour = System.DateTime.Now.Hour;
minutes = System.DateTime.Now.Minute;
}
public void Night()
{
//change light settings
GL.GetComponent<Light2D>().Intensity = 0.4;
}
}
To reference the Light2D Component you need to add the UnityEngine.Experimental.Rendering.Universal namespace to your code.
Namespace Example:
...
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
public class DayNight : MonoBehaviour
{
...
}
If you get an Error you need to just continue and try to compile it, to see if it actually works.
After that is done you should be able to access the Light2D Component of your GameObject without any further troubles.
Calling Light2D Example:
public float nightvalue = 0.4f;
public void Night()
{
// Change light intensity to nightvalue.
GL.GetComponent<Light2D>().intensity = nightvalue;
}
I am trying to change mass of a 3D object programmatically. But the object doesn't get the calculated mass but a 0 value initially. When the prefab of the object is created it gets the calculated mass of the previous object not the current mass. And the scenario repeats for all the prefabs created henceforth. How can I get around this problem? Any help is greatly appreciated.
You're probably missing a get component call:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public float mass;
public Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
rb.mass = 0.5f;
}
}
To give your rigidbody a mass can use the following script wise
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Example() {
rigidbody.mass = 0.5F;
}
}
Next time do some more research.
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-mass.html
Google first hit.