I have a Prefab called "Piece"
, for all the different board game pieces. They all have different 3D models. Also a ScriptableObject
associated with the prefab that contains a reference to the 3D piece model gameObject
, so I can change it out to whatever piece and have that model displayed.
public Piece piece;
private GameObject character;
...
character = GameObject.Find("Character");
...
character = piece.character;
The problem is
I don’t know how to actually replace or swap an entire collection of 3D objects in the Piece Prefab based on the given GameObject
. I do a very similar thing but with a Card Prefab with sprites, but that just requires me to change the Sprite Renderer
component of the Prefab which is simpler and doesn’t require replacing the whole GameObject
.
So how could I go about doing this?
Thanks.
To anyone wondering, I got this solved for what I was trying to do:
public Piece piece;
public GameObject modelContainer;
public void SetPieceModel(GameObject model) {
// Check if model container is assigned
if (modelContainer == null) {
Debug.LogError("modelContainer is not assigned in the Inspector.");
return;
}
// Remove any existing models
foreach (Transform child in modelContainer.transform) {
Destroy(child.gameObject);
}
// Instantiate and assign the new model
GameObject newModel = Instantiate(model, modelContainer.transform);
newModel.transform.localPosition = Vector3.zero;
newModel.transform.localRotation = Quaternion.identity;
}
Then if you want to spawn/set a piece at runtime with the desired model you could do something like this:
void SpawnPiece()
{
// Instantiate a new piece prefab
GameObject newPiece = Instantiate(piecePrefab);
// Get the PieceController component of the new piece
PieceController pieceController = newPiece.GetComponent<PieceController>();
if (pieceController != null)
{
// Set the piece's model based on the ScriptableObject data
pieceController.SetPieceModel(pieceData.pieceModel);
}
else
{
Debug.LogError("Piece prefab is missing the PieceController script.");
}
}
Hopefully it helps someone else as it did me.