C# Classes accessed by Javascripts

Hi Guys,

This has been asked before but no one spends time on explaining a working example, so I still can’t get it working. I would like to access my class in a Javascript. Please go through the step by step process. Here is a very simplified version of what I have:

  1. I have this class, in my plugins folder in the root called Defect.cs (It’s not attached to any game object or anything, its just sitting in my directory)
using UnityEngine;
using System.Collections;

public class Defect : MonoBehaviour {
	public string words
	{
		get
		{
			return words;
		}
		set
		{
			words = value;
		}
	}
	// Use this for initialization
	void Start () {
	this.words = "nothing";
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
  1. I try to access it via a javascript that is attached to a transform in my scene with this function:
function test()
{
var defvar = new Defect();
}
  1. I get the following error :
    Assets/Standard Assets/Scripts/Camera Scripts/MouseOrbit_Custom.js(56,18): BCE0005: Unknown identifier: ‘Defect’.

What am I doing wrong?

The JS script is in the same compilation level (see here); move it out of Plugins or Standard Assets. You can’t use that code anyway, since the Defect class extends MonoBehaviour, which means it can only be attached to an object with AddComponent, it can’t be created with New. There’s no reason to mix languages like this in any case; just do it all in JS and save yourself the bother of messing with script compilation order like this.

–Eric

1st of all you need to put .cs file into the Standard Assets folder.
2nd you need to create variable of C# class in .js file lke this : If Defect.cs is your c# file then in .js file you need to take private var defectvar :smile:efect; in your java script file. Then you simple communicate with both file.

No, I already explained the problem above. Putting the .cs file in Plugins is fine, but the .js script cannot be in Plugins or Standard Assets.

–Eric

Thanks Gents. All my JS scripts exist in Standard assets. It worked fine up to this point. I’m only now experimenting with creating a c# class and wanted to see how the cross collaboration worked.