- Home /
How do I use JS to access C# methods/classes?
I have 2 scripts -- a C# script that does some math, and one JS/UnityScript that should utilize its methods. Only the UnityScript is attached to a game object.
For some reason, no matter how I set up the scripts or variables, I keep getting the "Unknown identifier: OSM" BCE0005 error. I've even went so far as to put the C# script into a Plugins folder so it will compile earlier, but for some reason, the JS still can't see the OSM class and its methods!
Here's my code (Note, the Update function is omitted for brevity):
Javascript :
function MapPosition() {
var tx : Vector2;
tx = OSM.WorldToTile(fixLon,fixLat);
}
C# :
using UnityEngine;
using System.Collections;
using System;
public class OSM {
public Vector2 WorldToTile(double lon, double lat, int zoom)
{
Vector2 p = new Vector2();
p.x = (float)((lon + 180.0) / 360.0 * (1 << zoom));
p.y = (float)((1.0 - Math.Log(Math.Tan(lat * Math.PI / 180.0) +
1.0 / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom));
return p;
}
public Vector2 TileToWorld(double tile_x, double tile_y, int zoom)
{
Vector2 p = new Vector2();
double n = Math.PI - ((2.0 * Math.PI * tile_y) / Math.Pow(2.0, zoom));
p.x = (float)((tile_x / Math.Pow(2.0, zoom) * 360.0) - 180.0);
p.y = (float)(180.0 / Math.PI * Math.Atan(Math.Sinh(n)));
return p;
}
}
Answer by awesomedata · Dec 18, 2016 at 12:15 AM
It required being put into a new project for some reason. After that, it worked fine. I'm assuming it was a fluke with my asset database or something. :/
Sooo strange... :(
Answer by NorthernVisionStudio · May 11, 2015 at 04:01 PM
You are trying to use the OSM class without an object instantiation. Please try
1) new OSM object before calling methods
OR
2) make the methods static so that you don't need an object instance to access them.
I've tried your first advice (since I want to eventually use coroutines) :
var osm = new OS$$anonymous$$();
var tx : Vector2;
tx = osm.WorldToTile(fixLon,fixLat);
...but I still receive the "unknown identifier" error.
How do I do the "new OS$$anonymous$$ object" thing you mentioned? I thought that what I did there was the proper way to instantiate a new class 'object' to call its methods?
$$anonymous$$ind giving a code example on how to do either of these???
Apparently even making it static doesn't help... I can't find help for this anywhere on the net. Any ideas? Anyone...?
I just copied and pasted your code into a new project. The JS file was in Assets and the CS file was in Plugins folder. I added 'static' to each method.
No problems on my end.
Your answer
![](https://koobas.hobune.stream/wayback/20220613195335im_/https://answers.unity.com/themes/thub/images/avi.jpg)