Getting an error when trying to use a string with meshes in unity:
Cannot implicitly convert type 'UnityEngine.Mesh' to 'UnityEngine.Mesh[]'
EC: error CS0029: Cannot implicitly convert type 'UnityEngine.Mesh' to 'UnityEngine.Mesh[]'
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class HatSwitch : MonoBehaviour
{
[SerializeField] private MeshFilter modelYouWantToChange;
[SerializeField] private Mesh[] modelYouWantToUse;
private int currentModel;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
modelYouWantToChange.mesh = modelYouWantToUse[currentModel];
currentModel ;
if (currentModel >= modelYouWantToUse.Length)
{
currentModel = 0;
}
}
}
public void ChangeMeshButton()
{
modelYouWantToChange.mesh = modelYouWantToUse[currentModel];
currentModel ;
if (currentModel >= modelYouWantToUse.Length)
{
currentModel = 0;
}
}
public void ChangeMeshButtonBack()
{
modelYouWantToChange.mesh = modelYouWantToUse[currentModel];
currentModel--;
if (currentModel >= modelYouWantToUse.Length)
{
currentModel = 0;
}
}
}
Trying to create a skin changer for a game :
CodePudding user response:
I don't know which line is causing the exception, it's not clear how the modelYouWantToUse
array is being populated, and I don't know Unity at all, but here's how I would do it:
public class HatSwitch : MonoBehaviour
{
[SerializeField] private MeshFilter modelToChange;
[SerializeField] private Mesh[] meshItems;
private int currentMeshIndex = 0;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) ChangeMesh();
}
public void ChangeMesh()
{
// Update the mesh
modelToChange.mesh = meshItems[currentMeshIndex];
// Increment our index
currentMeshIndex ;
// Validate index is in range
if (currentMeshIndex >= meshItems.Length) currentMeshIndex = 0;
}
public void ChangeMeshBack()
{
// Update the mesh
modelToChange.mesh = meshItems[currentMeshIndex];
// Decrement our index
currentMeshIndex--;
// Validate index is in range
if (currentMeshIndex < 0) currentMeshIndex = meshItems.Length - 1;
}
}