- Home /
Converting Script from Java to C#
I usually don't do this kind of stuff but could someone help me convert this? My biggest problem is to know what var type's h and w are. If someone could help me, it would be much appreciated!
@script ExecuteInEditMode()
var crosshair : Texture2D;
public var widthcross : int;
public var heightcross : int;
function OnGUI ()
{
var w = crosshair.width/widthcross;
var h = crosshair.height/heightcross;
position = Rect((Screen.width - w)/2,(Screen.height - h )/2, w, h);
GUI.DrawTexture(position, crosshair);
}
Questions like this are best asked in the Unity Forum since the title is not actually a question, and code conversion is rarely useful for future readers in Q&A format.
Sorry mate i'll remember that for next time. @Andy yeah I know I rushed the title a bit, but I mean it didn't really cause any confusion I guess.
Answer by numberkruncher · Sep 17, 2013 at 06:33 PM
Not tested, but something like the following should work:
using UnityEngine;
[ExecuteInEditMode]
public class YourScriptName : MonoBehaviour {
public Texture2D crosshair;
public int widthcross;
public int heightcross;
void OnGUI() {
// Only draw textures for repaint events.
if (Event.current.type == EventType.Repaint) {
int w = crosshair.width / widthcross;
int h = crosshair.height / heightcross;
Rect position = new Rect((Screen.width - w) / 2, (Screen.height - h) / 2, w, h);
GUI.DrawTexture(position, crosshair);
}
}
}
Answer by clunk47 · Sep 17, 2013 at 06:34 PM
Define a class, and import System.Collections and UnityEngine. Instead of using something like var widthcross : int, in C# this would be public int widthcross. Public makes properties available for changing in the inspector, as well as accessible from other scripts. Be sure to name your C# script the same as your class.
Example.cs
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class Example : MonoBehaviour
{
public Texture2D crosshair;
public int widthcross;
public int heightcross;
float w;
float h;
Rect position;
void OnGUI ()
{
w = crosshair.width/widthcross;
h = crosshair.height/heightcross;
position = new Rect((Screen.width - w)/2,(Screen.height - h )/2, w, h);
GUI.DrawTexture(position, crosshair);
}
}
Throw-away position rectangles are better handled within function scope since Rect
is a value type. Same goes for the other 2 temporary variables w
and h
. Accessing member variables is slower than accessing local variables since this
must first be dereferenced.
This also works but the other guy answered first, thank you anyway, voted your answer up!