I have some images in "assets/resource/mat" . I want to get this images and put them to array . But when I try to get this images I'm getting ArrayIndexOutOfBoundsException . I think that there is problem with Resource.LoadAll("mat") method . But I can't fix it . Please help me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour
{
private string t;
public Sprite[] Icons;
void Start()
{
Object[] loadedIcons = Resources.LoadAll("mat");
Icons = new Sprite[loadedIcons.Length];
for (int x = 0; x < loadedIcons.Length; x++)
{
Icons[x] = (Sprite)loadedIcons[x];
Debug.Log("Loading....");
}
GameObject sp = new GameObject();
sp.GetComponent<SpriteRenderer>().sprite = Icons[0];
}
}
Loading all images from a particular folder, with LINQ, would look like this...
using UnityEngine;
using System.Linq;
public class Four : MonoBehaviour
{
public Sprite[] icons;
void Start()
{
icons= Resources.LoadAll("met", typeof(Sprite)).Cast<Sprite>().ToArray();
}
}
I'm not sure but I guess you instead of Sprite first have to load a Texture2D and then create a Sprite from it.
Also note you used GetComponent<SpriteRenderer>() on a newly created empty GameObject so obviously there will never be a SpriteRenderer component attached. Instead use AddComponent.
Sprite[] Icons;
Texture2D LoadedTextures;
private void Start()
{
LoadedTextures = (Texture2D[])Resources.LoadAll("mat", typeof(Texture2D));
Icons = new Sprite[loadedIcons.Length];
for (int x = 0; x < loadedIcons.Length; x++)
{
Icons[x] = Sprite.Create(
LoadedTextures[x],
new Rect(0.0f, 0.0f, LoadedTextures[x].width, LoadedTextures[x].height),
new Vector2(0.5f, 0.5f),
100.0f);
}
GameObject sp = new GameObject();
// Note that here you created a new empty GameObject
// so it obviously won't have any component of type SpriteRenderer
// so add it instead of GetComponent
sp.AddComponent<SpriteRenderer>().sprite = Icons[0];
}
Related
I have created a script who will spawn objects and give tag and color for one element of prefab. But script not working with clones. This 2 scripts, GameManager( he must spawn objects) and
RandomTagAndColor( he give to element of prefab tag and name). And in scene of game, where objects is spawning, script give tag and colour only to first prefab. In game those prefabs 10. Well, I'm sorry if question is stupid, this first thing, what i doing without books,guides.
GameManager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class GameManager : MonoBehaviour
{
// Start is called before the first frame update
public GameObject firstBarrier;
public GameObject secondBarrier;
public int numOfBarriers = 0;
System.Random rnd = new System.Random();
System.Random rndY = new System.Random();
Vector3 vector = new Vector3(5, 1/3 , 1);
void Start()
{
for (numOfBarriers = 0; numOfBarriers < 10; numOfBarriers++)
{
int ewq = rnd.Next(1, 20);
int rY = rndY.Next(1, 4);
if(ewq <= 10)
{
Instantiate(firstBarrier, vector, Quaternion.identity);
}
else
{
Instantiate(secondBarrier, vector, Quaternion.identity);
}
vector.x -= 7;
vector.y = rY;
}
}
void Update()
{
}}
RandomColorAndTag script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class RandomColorAndTag : MonoBehaviour
{
GameObject Bar;
System.Random randomElement = new System.Random();
int el = 0 ;
void Start()
{
el = randomElement.Next(2, 6);
GameObject.Find($"Cube ({el})").GetComponent<Renderer>().material.color = Color.green;
if (GameObject.Find($"Cube ({el})").GetComponent<Renderer>().material.color == Color.green)
{
GameObject.Find($"Cube ({el})").transform.tag = "Green";
}
}
void Update()
{
}
}
As mentioned there are lot of unclear issues in your codes.
I will assume the RandomColorAndTag is attached to the objects you spawn. In that case don't use Find but rather simply assign the random color and tag to yourself
what is a random value between 1 and 19 good for, of all you ever do with it is check whether it is bigger or smaller than 10? => Simply use only a random 0 or 1 and check whether it is 0 ;)
I'm unsure exactly what items should be green now .. I assume among the 10 spawned items you want to pick one and make it special..
finally I wouldn't even let the objects assign their own tag and color but let the GameManager trigger it
So I would do something like
public class GameManager : MonoBehaviour
{
public TagAndColorController fortBarrier;
public TagAndColorController secondBarrier;
public int numOfBarriers = 10;
public Vector3 vector = new Vector3(5, 1f/3f , 1);
public Color specialColor = Color.Green;
public string specialTag = "Green";
private void Start()
{
var specialIndex = Random.Range(0, numberOfBarriers);
for (var i = 0; i < numOfBarriers; i++)
{
// upper bound is exclusive -> this returns 0 or 1
var rndBarrier = Random.Range(0, 2);
// not sure if intended but again: upper bound is exclusive -> this return 1, 2, or 3
var rY = Random.Range(1, 4);
var tagAndColor = Instantiate(rndBarrier == 0 ? firstBarrier : secondBarrier, vector, Quaternion.identity);
if(i == numberOfBarriers)
{
tagAndColor.SetColorAndTag(specialColor, specialTag);
}
vector.x -= 7;
vector.y = rY;
}
}
}
And the other script has no logic whatsoever but rather only is a quick access to the objects renderer and bundles the behavior
public class TagAndColorController : MonoBehaviour
{
[SerializeField] private Renderer _renderer;
public void SetColorAndTag(Color newColor, string newTag)
{
gameObject.tag = newTag;
if(!_renderer) _renderer = GetComponent<Renderer>();
_renderer.material.color = newColor;
}
}
I want to sort 5 spheres in Unity by using sorting algorithms. They will swap places in sorted order after I click sort button. I manage to create a list for gameobjects but as I understand it is only sorting the list then do nothing. How to create such script that I want? It will swap objects by gameobject name. The Envrioment,
the code that I made so far;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Assets
{
class Gameobjects : MonoBehaviour
{
public Button s_YourButton;
[SerializeField]
private GameObject[] deck;
public List<GameObject> instanciatedObjects;
void Start()
{
Button btn = s_YourButton.GetComponent<Button>();
//Calls the TaskOnClick method when you click the Button
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
Fill();
instanciatedObjects = instanciatedObjects.OrderBy(Sphere => Sphere.name).ToList();
}
public void Fill()
{
instanciatedObjects = new List<GameObject>();
for (int i = 0; i < deck.Length; i++)
{
instanciatedObjects.Add(Instantiate(deck[i]) as GameObject);
}
}
}
}
Any idea is welcome for me to do futher research, I am new to Unity.
First you can do is store a list of Vector3 of the old one. basicly List.Add(spawnedObject.transform.position); inside the for loop in Fill().
Then after you sorted them, you loop the instanciatedObjects and set them in the same order as the Vector3 list.
List<Vector3> vectorList = new List<Vector3>();
void TaskOnClick()
{
Fill();
instantiatedObjects = instantiatedObjects.OrderBy(Sphere => Sphere.name).ToList();
for(int i = 0; i < instanciatedObjects.Count; i++)
{
instantiatedObjects[i].transform.position = vectorList[i];
}
}
public void Fill()
{
vectorList.Clear();
instantiatedObjects = new List<GameObject>();
for (int i = 0; i < deck.Length; i++)
{
GameObject spawnedObject = Instantiate(deck[i]) as GameObject;
instantiatedObjects.Add(spawnedObject);
vectorList.Add(spawnedObject.transform.position);
}
}
btw, a typo in your code: instanciatedObjects should be instantiatedObjects
I have a issue with a script. I am trying to create a star field randomly in a sphere for my unity scene. But I am new to unity and c# so I am a bit confused.
The stars have a fixed place so they should not move and so are created in Start(); and then are drawn in Update();
The problem is I get this error:
MissingComponentException: There is no 'ParticleSystem' attached to the "StarField" game object, but a script is trying to access it.
You probably need to add a ParticleSystem to the game object "StarField". Or your script needs to check if the component is attached before using it.
Stars.Update () (at Assets/Stars.cs:31)
If i add a particle system component manually it causes a load of big flashing orange spots, which i don't want, so i want to add the component in the script some how.
This is my script attached to an empty game object:
using UnityEngine;
using System.Collections;
public class Stars : MonoBehaviour {
public int maxStars = 1000;
public int universeSize = 10;
private ParticleSystem.Particle[] points;
private void Create(){
points = new ParticleSystem.Particle[maxStars];
for (int i = 0; i < maxStars; i++) {
points[i].position = Random.insideUnitSphere * universeSize;
points[i].startSize = Random.Range (0.05f, 0.05f);
points[i].startColor = new Color (1, 1, 1, 1);
}
}
void Start() {
Create ();
}
// Update is called once per frame
void Update () {
if (points != null) {
GetComponent<ParticleSystem>().SetParticles (points, points.Length);
}
}
}
How can i set it to get a static star field, because adding a particle system component manually gives me these annoying orange particles and am wanting to do it purely via scripts.
It will be easier for you if you add the particle system manually and change the settings so that you don't see any funny shapes at runtime or in the Editor.
As a side note, you don't need to set the particles every frame in Update. Even if you did, calling GetComponent is expensive, so you should save the ParticleSystem as a field of the class in the Start() method.
Here is some modified code that worked for me:
using UnityEngine;
public class Starfield : MonoBehaviour
{
public int maxStars = 1000;
public int universeSize = 10;
private ParticleSystem.Particle[] points;
private ParticleSystem particleSystem;
private void Create()
{
points = new ParticleSystem.Particle[maxStars];
for (int i = 0; i < maxStars; i++)
{
points[i].position = Random.insideUnitSphere * universeSize;
points[i].startSize = Random.Range(0.05f, 0.05f);
points[i].startColor = new Color(1, 1, 1, 1);
}
particleSystem = gameObject.GetComponent<ParticleSystem>();
particleSystem.SetParticles(points, points.Length);
}
void Start()
{
Create();
}
void Update()
{
//You can access the particleSystem here if you wish
}
}
Here is a screenshot of the starfield with the settings used in the particle system. Note that I switched off looping and play on awake.
I would like to edit 1 vertex on a cube, but I don't know how to. I've tried looking everywhere for this function, but I can't find a solution.
Here is an image of what I want to achieve:
http://answers.unity3d.com/questions/14567/editing-mesh-vertices-in-unity.html
This code is not mine. Bellow is the same code as the link above. I just separated it into two files. (one per class)
It work quite good. BUT make sure to save you scene before using it, it's a bit buggy.
Don't forget to leave edit mode when you are done whit your modification.
You don't need to add "editMesh" tag to the gameobject you are modifying, or it will be erased when you leave edit mode.
Lastly, if you modify a primitive from unity, the modification will be applied for every instance of that primitive ! (if you change a cube for a pyramid, every cube will become a pyramid)
To avoid that make a copy of your primitive mesh, change the mesh you are using in your mesh renderer by your copy and then modify it. (bellow a script to add simple copy function in unity menu)
EditMesh.cs
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
/// <summary>
/// http://answers.unity3d.com/questions/14567/editing-mesh-vertices-in-unity.html
/// </summary>
[AddComponentMenu("Mesh/Vert Handler")]
[ExecuteInEditMode]
public class EditMesh : MonoBehaviour {
public bool _destroy;
private Mesh mesh;
private Vector3[] verts;
private Vector3 vertPos;
private GameObject[] handles;
private const string TAG_HANDLE = "editMesh";
void OnEnable() {
mesh = GetComponent<MeshFilter>().sharedMesh; // sharedMesh seem equivalent to .mesh
verts = mesh.vertices;
foreach (Vector3 vert in verts) {
vertPos = transform.TransformPoint(vert);
GameObject handle = new GameObject(TAG_HANDLE);
// handle.hideFlags = HideFlags.DontSave;
handle.transform.position = vertPos;
handle.transform.parent = transform;
handle.tag = TAG_HANDLE;
handle.AddComponent<EditMeshGizmo>()._parent = this;
}
}
void OnDisable() {
GameObject[] handles = GameObject.FindGameObjectsWithTag(TAG_HANDLE);
foreach (GameObject handle in handles) {
DestroyImmediate(handle);
}
}
void Update() {
if (_destroy) {
_destroy = false;
DestroyImmediate(this);
return;
}
handles = GameObject.FindGameObjectsWithTag(TAG_HANDLE);
for (int i = 0; i < verts.Length; i++) {
verts[i] = handles[i].transform.localPosition;
}
mesh.vertices = verts;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
}
}
#endif
EditMeshGizmo.cs
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
/// <summary>
/// http://answers.unity3d.com/questions/14567/editing-mesh-vertices-in-unity.html
/// </summary>
[ExecuteInEditMode]
public class EditMeshGizmo : MonoBehaviour {
private static float CURRENT_SIZE = 0.1f;
public float _size = CURRENT_SIZE;
public EditMesh _parent;
public bool _destroy;
private float _lastKnownSize = CURRENT_SIZE;
void Update() {
// Change the size if the user requests it
if (_lastKnownSize != _size) {
_lastKnownSize = _size;
CURRENT_SIZE = _size;
}
// Ensure the rest of the gizmos know the size has changed...
if (CURRENT_SIZE != _lastKnownSize) {
_lastKnownSize = CURRENT_SIZE;
_size = _lastKnownSize;
}
if (_destroy)
DestroyImmediate(_parent);
}
void OnDrawGizmos() {
Gizmos.color = Color.red;
Gizmos.DrawCube(transform.position, Vector3.one * CURRENT_SIZE);
}
}
#endif
CopyMesh.cs (put it in a directory named "Editor") (you should then find it in your menu bar)
using UnityEditor;
using UnityEngine;
namespace Assets {
/// <summary>
///
/// </summary>
public class CopyMesh : MonoBehaviour {
[MenuItem("Assets/CopyMesh")]
static void DoCopyMesh() {
Mesh mesh = Selection.activeObject as Mesh;
Mesh newmesh = new Mesh();
newmesh.vertices = mesh.vertices;
newmesh.triangles = mesh.triangles;
newmesh.uv = mesh.uv;
newmesh.normals = mesh.normals;
newmesh.colors = mesh.colors;
newmesh.tangents = mesh.tangents;
AssetDatabase.CreateAsset(newmesh, AssetDatabase.GetAssetPath(mesh) + " copy.asset");
}
[MenuItem("Assets/CopyMeshGameObject")]
static void DoCopyMeshGameObject() {
Mesh mesh = (Selection.activeGameObject.GetComponent<MeshFilter>()).sharedMesh;
Mesh newmesh = new Mesh();
newmesh.vertices = mesh.vertices;
newmesh.triangles = mesh.triangles;
newmesh.uv = mesh.uv;
newmesh.normals = mesh.normals;
newmesh.colors = mesh.colors;
newmesh.tangents = mesh.tangents;
print(AssetDatabase.GetAllAssetPaths()[0]);
AssetDatabase.CreateAsset(newmesh, AssetDatabase.GetAllAssetPaths()[0] + "/mesh_copy.asset");
}
}
}
Lately Unity has added access to the ProBuilder package via "Package Manager".
More info here:
https://docs.unity3d.com/Packages/com.unity.probuilder#4.0/manual/index.html
Unity editor has no built-in mesh editor capabilities at the moment.
I can advise you using Prototype plugin for that.
You can easily do that by iterating through the Vertices, which Unity will give you as a Vector3[] through the someObject.GetComponent<MeshFilter>().vertices field. See http://docs.unity3d.com/ScriptReference/Mesh-vertices.html for an example where the vertices are moved upwards with time.
I'm trying to get variable from an empty gameObject's script, but I can't assign that gameObject on the inspector. These are the screen shots and codes from my game.
Well, I have this code to load when the game is starting. Land and Prince are objects that made from this code.
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class loadGame : MonoBehaviour
{
public static loadGame loadSave;
public GameObject objPrince;
public Pangeran charPrince;
public Transform prefPrince;
public Sprite[] spriteTanah;
public Dictionary<string, Tanah> myTanah = new Dictionary<string, Tanah>();
public Dictionary<string, GameObject>objTanah = new Dictionary<string, GameObject>();
public Tanah tempTanah;
public GameObject tempObjTanah;
public Transform prefTanah;
public float mapX;
public float mapY;
public int i = 0;
public int j = 0;
public int rows = 9;
public int column = 9;
void Awake(){
if(loadSave == null)
{
DontDestroyOnLoad(gameObject);
loadSave = this;
}
else if(loadSave != this)
Destroy(gameObject);
}
// Use this for initialization
void Start ()
{
Load ();
}
// Update is called once per frame
void Update ()
{
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
}
else
{
charPrince = new Pangeran ("Prince", "04Okt1993", 0, 0, 0, 0, 0, false, false);
objPrince = GameObject.Instantiate (prefPrince, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
//objPrince.name = "Prince";
charPrince.locationY = 0f;
charPrince.locationX = 0f;
charPrince.hadapAtas = false;
charPrince.hadapKanan = true;
charPrince.stamina = 100f;
charPrince.exp = 0f;
charPrince.speed = 0f;
for(i = 0 ; i < rows ; i ++)
{
for(j = 0; j<column ; j++)
{
mapX = (i-j) * 0.8f;
mapY = (i+j) * 0.4f;
if(i>=1 && j>=1 && i<=5 && j<=5)
{
prefTanah.name = "land-"+j.ToString("0#")+"-"+i.ToString("0#");
tempTanah = new Tanah("land-"+j.ToString("0#")+"-"+i.ToString("0#"),mapX,mapY,"land",spriteTanah[0],spriteTanah[1],spriteTanah[2]);
myTanah.Add("land-"+j.ToString("0#")+"-"+i.ToString("0#"),tempTanah);
tempObjTanah = GameObject.Instantiate(prefTanah, new Vector3(mapX,mapY,0),Quaternion.identity)as GameObject;
objTanah.Add("land-"+j.ToString("0#")+"-"+i.ToString("0#"),tempObjTanah);
}
else
{
prefTanah.name = "snow-"+j.ToString("0#")+"-"+i.ToString("0#");
tempTanah = new Tanah("snow-"+j.ToString("0#")+"-"+i.ToString("0#"),mapX,mapY,"snow");
myTanah.Add("snow-"+j.ToString("0#")+"-"+i.ToString("0#"),tempTanah);
tempObjTanah = GameObject.Instantiate(prefTanah, new Vector3(mapX,mapY,0),Quaternion.identity)as GameObject;
objTanah.Add("snow-"+j.ToString("0#")+"-"+i.ToString("0#"),tempObjTanah);
}
}
}
}
}
}
I'm trying to access one of some variables from code above, but I can't assign it in the inspector.
but I can't do it.
please help me. Thank you.
The problem is that the loadLand variable is of type LoadGame which is a script. What you are trying to do is to add a GameObject to this variable. So change the public variable type to
public GameObject LoadLandObject;
private LoadGame loadLand;
and create a private LoadGame variable which is the reference to your script.
Add in the Start() method
loadLand = (LoadGame)LoadLandObject.GetComponent<LoadGame>();
With this you load the script LoadGame of the GameObject into the variable.
Do you ever set your plantingScript.loadLand to the instance of loadGame.loadSave? This must be done after Awake in your case to be sure the instance has been set.
Can I ask, what are you trying to do?
You should simply just assign you loadGame script in the inspector of plantingScript and not use statics at all. They will bite your ass sooner or later (and I'm guessing it already is).
Have a similar problem. Did n't find simple and clear solution. May be what i did help to you.
Create empty game object.
Attach loadGame.cs to it (if you whant to control when script starts - uncheck it,in this case don't foget to set loadLand.enabled to true in plantingScript when needed)
Drag this object to you loadLand field
Sample project