They appearing in Play Mode in Scene View and in Game View. But when i build and run the project, they are not visible. I’ve deleted all other sprites from the scene to exclude sorting layer problems. But still no effect. Any ideas?
P.S. renderer.isVisible always false for all objects. Why is that?
There’s no Resources.LoadAssetAtPath available in a build. There are no individual files in a build; .jpg and so on are never used aside from importing into the editor. (BTW, don’t use .jpg, it’s lossy.)
The best way would be not to do all this in the first place, but just instantiate prefabs.
public GameObject mySpritePrefab;
public void AddSprite (Vector2 pos) {
var sprite = Instantiate (mySpritePrefab) as GameObject;
sprite.transform.position = pos;
}
Okay, thanks! But where will i get mySpritePrefab object? Sorry, i just starting to learn Unity. Is mySpritePrefab will be some sort of prorotype? Do i need to create instance of it somewhere?
P.S. I need sprite to have different coordinates of an image every time. In fact i posted a question of what i need exactly here, but no one replied.
I red prefab manual and created prefab in editor. But i still can’t understand how can i access my prefab from editor in the script? There is always some “myPrefab” member of the class. But how instantiate itself? myPrefab = GameObject.Find("Mask Rect"); is not working.
Make a public variable that you use for the reference, as shown in my example. Drag and drop the prefab onto the appropriate slot in the inspector. Don’t use Find.
public class Mask : MonoBehaviour {
static Mask instance = null;
public static Mask inst {
get {
if (instance == null) instance = GameObject.FindObjectOfType<Mask>();
return instance;
}
}
public GameObject spritePrefab;
public void add(Vector2 pos, float width, float height) {
Sprite sprite = Instantiate(spritePrefab) as Sprite;
Debug.Log (sprite);
}
}
and prefab attached to it. Now i need to use it as a singleton, but GameObject.FindObjectOfType<Mask>(); find nothing. How can i create an instance of it?
That worked, sprite appears.
P.S. [quote=“Eric5h5, post:10, topic: 561672, username:Eric5h5”]
Also, you can just say “instance = this”.
[/quote]
it is static method. Outside Unity in C# i can’t use members of instance in static methods. How it works in unity?
P.S.S. No, do i need to attach it to an existing object? Can’t i just “create” one myself in the script?
P.S.S.S.
public void add(Rect rect) {
var obj = Instantiate (spritePrefab) as GameObject;
SpriteRenderer renderer = obj.renderer as SpriteRenderer;
Sprite newSprite = Sprite.Create(renderer.sprite.texture, rect, new Vector2(0f, 0f), 100f);
renderer.sprite = newSprite;
}