- Home /
Javascript to C# Conversion Question
This should be an easy fix but I just can't seem to think of how to apply MonoBehavior or an inheritance class to this. I frankly don't know where to go with this. I translated it from Javascript. Obviously I need to add a few lines, but I can't think of what I need to add. Here is the original:
@script ExecuteInEditMode
var theLight : Transform;
function Update ()
{
renderer.sharedMaterial.SetVector("_WorldLightDir", -theLight.forward);
}
And where I am at this point:
[ExecuteInEditMode]
Transform theLight;
void Update () {
renderer.sharedMaterial.SetVector("_WorldLightDir", -theLight.forward);
}
Any pointers?
Answer by clunk47 · Jul 23, 2013 at 12:15 AM
You have to define the class(public class Example), and import references (UnityEngine and System.Collections in this example). Here is an example. Say for example's sake, your script name is Example.cs. Then your class name would be Example.
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class Example : MonoBehaviour
{
public Transform theLight;
void Update()
{
//Your code here.
}
}
Notice I say public on the transform. That's because by default in C#, objects are private, unlike JS. So if you need something to show up in the inspector, you need to make it public.
Yes and no. That was the first thing I decided that I neede to do, however I didn't know if I needed to inherit from anything or make it make it monobehaviour. I decided to leave it without either and see if it causes any problems later on when I'm wrapping everything up (: thank you.
It usually needs to be a $$anonymous$$onoBehaviour, since $$anonymous$$onoBehaviour is the class every script derives from, at least every script you use in your actual game. Some script, like Editor scripts can derive from System.Object. Click Here for more clarification.
Ok, have you got a C# script running in Unity then?
using UnityEngine;
using System.Collections;
public class Example : Component
{
void Awake()
{
Debug.Log ("TEST");
}
}
Won't work. You'll just get a warning.
The class defined in the script file named 'Example' is not derived from $$anonymous$$onoBehaviour or ScriptableObject!
Using Javascript every script automatically derives from $$anonymous$$onoBehaviour. When using C# or Boo you have to explicitly derive from $$anonymous$$onoBehaviour.
Did you read the documentation I linked you to?