Translate C# into Js

Hi folks,

I got this C#, but I have no experience with C#. Is there someone who can translate this C# script into JavaScript?

using UnityEngine;
using System.Collections;

public class MyUnitySingleton : MonoBehaviour {
 
private static MyUnitySingleton instance = null;
public static MyUnitySingleton Instance
{
	get
	{
		return instance;
	}
}

void Awake()
{
	if (instance != null && instance != this)
	{
		Destroy(this.gameObject);
		return;
	}
	else
	{
		instance = this;
	}
	
	DontDestroyOnLoad(this.gameObject);
    }
}

Thanks in advance.

Have you at least tried converting it? This script is fairly easy to convert, even without C# knowledge. I will gladly help, if you write which part of this script you have problem with.

There´s another solution: forget javascript and learn the joy of C# :D

1 Answer

1

There are two errors in your conversion:

  1. you declare variables in UnityScript differently:

    private var instance : MyUnitySingleton = null;

  2. getter in US is declared in this way:

    public function get Instance() : MyUnitySingleton { return instance; }

Awake is ok.

Thanks, It works perfect. If I leave the scene, the music is still playing. But if I return to that scene where the script is. The sound is playing again. While the song is already playing. That means you hear the same sound twice ate one time. How to solve this problem?

It's hard to answer this question without knowing how you're using this script. But I think you should post it as a separate question, as this problem is unrelated to the original one. This way more users will be able to help.

Sounds like your gameObject is an AudioSource. Your music is running over itself because when you don't destroy a gameObject, and reload the scene, the original gameObject is left in the scene along with your new one.

Shouldn't this new one be destroyed in Awake? Condition of first if should eval to true.

I tried a lot, but the problem is still unsolved. It plays all over again when I return to the scene with that MusicObject. The Music plays over the same Music. Help please