Checking current scene name using SceneManager - c#

So I've decided to split my game into separate scenes(main menu, gameover, etc.) And I'm trying to use an if statement in my code to check if the current scene is "gameover" so I can perform some action. I know Unity now uses SceneManager instead of Application, but what's the equivalent of this function
if(Application.loadedLevelName == "gameover")
I've tried SceneManager.GetActiveScene == "gameover"
But I just get errors like can't use == here.
I have imported SceneManager aswell

You're getting an error here because SceneManager.GetActiveScene() returns an object of type SceneManager.Scene, not a string. However, according to the documentation, this gives you access to the public Scene.name, which is a string.
So the non-deprecated equivalent of:
if (Application.loadedLevelName == "gameover") {
// ...
}
Would be:
if (SceneManager.GetActiveScene().name == "gameover") {
// ...
}

Related

Comparison between InputField text and the answer text doesn't work properly; Unity3d; C#

I am trying to make a game where the player is controlled by an input field. When I try to store the value or the written text from the input field in a String and the compare the string to the solution string, it doesn't work. I have tried to work with debug.log functions everywhere to see when the code stops working, but I still can't see what the problem is. I have been looking for YouTube videos, unity-& other game development forums, but none of the proposed solutions seem to work with my code. I am fairly new to game development, and so maybe the solution is easy.
Here is the code i used but doesn't work as expected:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InputFieldComparision : MonoBehaviour
{
public InputField inputFieldInMainUi;
private string Txt;
void Update()
{
Txt = inputFieldInMainUi.text.ToUpper();
Debug.Log(Txt);
#region comparison
if (Txt == "MR")
{
Debug.Log("Move Right");
}
else if (Txt == "MM")
{
Debug.Log("move middle");
}
else if (Txt == "ML")
{
Debug.Log("move left");
}
else if (Txt == "J")
{
Debug.Log("jump");
}
else if (Txt == "M")
{
Debug.Log("menu");
}
else if (Txt == "Q")
{
Debug.Log("quit");
}
#endregion
}
}
I think the code doesn't store the value of the Input field in the String properly and therefore can't be compared.
First of all the == operator is used to compare the reference identity. The Equals() method compares the content.
Change your code using Equals() method like:
if (Txt.Equals("MR"))
{
Debug.Log("Move Right");
}
Make sure to bind/link the variable inputFieldInMainUi to the input field in your UI. I'm not familiar with Unity3D, but there should be an option to link the variable inputFieldInMainUi to the actual field.
Lastly try debugging and put a breakpoint at the line where you assign a value to Txt, make sure this variable contains the string-value that you want to compare to
Txt = inputFieldInMainUi.text.ToUpper();
Thank you very much to everybody who tried to help me with my problem, I was now finally able to find a solution. If you are interested in what was the problem I try to describe it to you: At the top of every unity-C# scrip we find the using tags, I didn't know you had to use a special using TMPro tag and therefore wasn't able to define my Inputfield as TMP_Inputfield. I once again what to thank you for your time and support :)

No image tracking subsystem found when you call ARTrackedImageManager.CreateRuntimeLibrary

I am trying to create a RuntimeReferenceImageLibrary and I have always this error:
NotSupportedException: No image tracking subsystem found. This usually
means image tracking is not supported.
UnityEngine.XR.ARFoundation.ARTrackedImageManager.CreateRuntimeLibrary
(UnityEngine.XR.ARSubsystems.XRReferenceImageLibrary
serializedLibrary) (at
Library/PackageCache/com.unity.xr.arfoundation#4.2.6/Runtime/AR/ARTrackedImageManager.cs:95)
Is there any way to change my subsystem and make it possible ?
I used the same project with the same XRReferenceImageLibrary and the ARTrackedImageManager and if you add the picture in the editor everything is working fine.
The problem is when you want to create a RuntimeReferenceImageLibrary for adding pictures in runtime.
//Definition
public XRReferenceImageLibrary serializedLibrary; //Set up in the editor
private ARTrackedImageManager trackedImageManager; //Set up in the awake function
I called this function in the Start function and also I tried to call it afterwards. Always I got the same result
private void TryOut()
{
if (trackedImageManager != null)
{
if (serializedLibrary != null)
{
if (trackedImageManager.enabled == true)
{
Debug.Log("Image manager and XR Reference found");
RuntimeReferenceImageLibrary runtimeLibrary = trackedImageManager.CreateRuntimeLibrary(serializedLibrary);
}
}
}
}

Question about PhotonNetwork.CurrentRoom.CustomProperties

When the game starts in multiplayer, the master client sends a PunRPC to have all clients run a function. This function tries to get the room properties to see if the game is active, if so it does something. For some reason a client gets a null reference error, but the master client does not. The strange thing is, a debug of the hash table for room properties is visible but I cannot get a specific item in it.
Tried Debugging the hash table to make sure that the key was set when the code was run. It was. "(System.String)ag=(System.Boolean)True ag=activeGame" This shows in Debug.Log(hash); But (bool)hash[rpk.activeGame] gets a null reference error. But only on the client side not the master client. So the key also works.
// Call all the clients to set up the room settings in the sub menu.
[PunRPC]
private void GameRoomSetup (string pOne, string pTwo, int pOneColor, int pTwoColor)
{
GameObject gameMenu = GameObject.Find ("GameMenu");
gameMenu.GetComponent<SubMenu> ().UpdatePlayers (pOne, pTwo, pOneColor, pTwoColor);
gameMenu.GetComponent<SubMenu> ().StartGameSetup ();
// If you are a player, change the active buttons that are visible.
if (PhotonNetwork.NickName == pOne || PhotonNetwork.NickName == pTwo)
{
gameMenu.GetComponent<GameButtonManager> ().GameStart ();
}
hash = PhotonNetwork.CurrentRoom.CustomProperties;
Debug.Log(hash);
if ((bool)hash[rpk.activeGame]) // Error on this line on client but not on master client. Says null reference.
{
GameObject.Find ("SoundManager").GetComponent<SoundManagerScript> ().PlayBackgroundTwo ();
GameObject.Find ("GameMenu").GetComponent<SubMenu> ().ChangeSubMenuActive (false);
}
}
I'm trying to run my if statement as a client but I get an error.
Thank you for choosing Photon!
To get a custom property, I recommend you use TryGetValue method as follows:
hash = PhotonNetwork.CurrentRoom.CustomProperties;
object temp;
string key = rpk.activeGame;
if (hash.TryGetValue(key, out temp))
{
if (temp is bool)
{
bool activeGame = (bool)temp;
}
else
{
// unexpected custom property value type
}
}
else
{
// custom property not found
}
If the custom property is not available yet, wait for the callback IInRoomCallbacks.OnRoomPropertiesUpdate(Hashtable propertiesThatChanged) (reference API).
Other notes and recommendations:
private void GameRoomSetup (string pOne, string pTwo, int pOneColor, int pTwoColor)
Not sure if it's supported or if it's a good idea to pass multiple parameters to a PUN RPC method.
To debug log a Dictionary or a Hashtable you could make use of SupportClass.DictionaryToString() method.
so instead of
Debug.Log(hash);
use
Debug.Log(SupportClass.DictionaryToString(hash));
Avoid calling expensive methods like GameObject.Find:
GameObject gameMenu = GameObject.Find ("GameMenu");
Also here you have duplicate calls to gameMenu.GetComponent<SubMenu>(), at least call it once and cache the component result found if any.
gameMenu.GetComponent<SubMenu> ().UpdatePlayers (pOne, pTwo, pOneColor, pTwoColor);
gameMenu.GetComponent<SubMenu> ().StartGameSetup ();
Comparing strings should not be done using == operator. At least use Equal method and proper StringComparison type. Read "How to compare strings in C#".
// If you are a player, change the active buttons that are visible.
if (PhotonNetwork.NickName == pOne || PhotonNetwork.NickName == pTwo)
{
gameMenu.GetComponent<GameButtonManager> ().GameStart ();
}
Besides, why do you use the Nickname to check if it's player one or two? maybe use ActorNumber or a custom player index. Or use the player count if the room is for 2 players only.

Exist control in current form?

I need to find out if component with some name exist in current form.
I have name of the component in string variable and if it doesnt exist, i need create it.
I use this code
Control c = Controls.Find(New, true)[0]; //najiti komponenty
if (c == null) {}
But it gives me error that the index was outside the bounds of the array.
I know this code is bad, but i dont know to write it good and google dont help me.
Find method return an array of controls, i.e. Control[]. You are trying to access the first element of the empty array, thus resulting in IndexOutOfRangeException
You should try:
Control[] controls = Controls.Find(New, true);
if (controls.Length > 0)
{
//logic goes here
}
else
{
//no components where found
}
Try using the Control.ContainsKey() Method, (pass a string variable containg the control name instead of the quoted text in my example):
if (!this.Controls.ContainsKey("MyControlName"))
{
// Do Something
}

How to lock in a single skeleton

I'm creating an application using the SDK, in which I must have only one user and lock it so if somebody else comes along, even if that person is closer to Kinect, the application keeps tracking the first skeleton it tracked.
From the msdn library I found I could use the Skeletom Stream Class:
Property: AppChoosesSkeletons = Gets or sets a Boolean value that determines whether the application chooses which skeletons to track.
Method: SkeletonStream.ChooseSkeletons (Int32) = Chooses one skeleton to track.
Syntax: public void ChooseSkeletons (int trackingId1)
I'm not very good at programming and I'm using C#, I thought of writing something like the code down, but it says that I'm using an Invalid Expression.
SkeletonFrame SFrame = e.OpenSkeletonFrame();
if (SFrame == null) return;
Skeleton[] Skeletons = new Skeleton[SFrame.SkeletonArrayLength];
SFrame.CopySkeletonDataTo(Skeletons);
int firstSkeleton = Skeletons[0].TrackingId;
sensor.SkeletonStream.ChooseSkeletons(int firstSkeleton);
if (firstSkeleton == null)
return;
if (SkeletonTrackingState.Tracked == firstSkeleton.TrackingState)
{
//body...
The problem is with the sensor.SkeletonStream.ChooseSkeletons(int firstSkeleton, it says int firstSkeleton cannot be used. Could someone please help me? Thanks!
sensor.SkeletonStream.ChooseSkeletons(int firstSkeleton);
What do you want to achive with this line ?
Imo if you want to cast firstSkeleton to int write it like this:
sensor.SkeletonStream.ChooseSkeletons((int) firstSkeleton);
if you don`t want to cast it and just to give and int variable to methid just write:
sensor.SkeletonStream.ChooseSkeletons(firstSkeleton);
You can not lock a skeleton, but you can choose the skeleton that you want to track, regardless of its position. It gets complicated when both people leave the Kinect's field of view.
By setting AppChoosesSkeletons to true you are able to chose the user that you want to track. To specify the user or users to track, call the SkeletonStream.ChooseSkeletons method and pass the tracking ID of one or two skeletons you want to track (or no parameters if no skeletons are to be tracked).
Something like this:
private void ChooseSkeleton()
{
if (this.kinect != null && this.kinect.SkeletonStream != null)
{
if (!this.kinect.SkeletonStream.AppChoosesSkeletons)
{
this.kinect.SkeletonStream.AppChoosesSkeletons = true; // Ensure AppChoosesSkeletons is set
}
foreach (Skeleton skeleton in this.skeletonData.Where(s => s.TrackingState != SkeletonTrackingState.NotTracked))
{
int ID { get.skeleton[1]}//Get ID here
}
if (ID = 0)
{
this.kinect.SkeletonStream.ChooseSkeletons(ID); // Track this skeleton
}
}
}

Categories