Make new GameObject in XNA 4(Create new instance) - c#

I have a Class for create GameObjects and it get's sprite and .... to make a game object.
And I draw my Texture like this :
spriteBatch.Begin();
foreach (GameObject gameObject in Game.gameObjects)
{
if (gameObject.visible)
{
spriteBatch.Draw(gameObject.sprite.texture, gameObject.rect, gameObject.sprite.sourceRect, gameObject.color, MathHelper.ToRadians(gameObject.rotation), gameObject.sprite.origin, gameObject.spriteEffect, gameObject.layer);
}
}
foreach (Text text in Game.texts)
{
spriteBatch.DrawString(text.font, text.text, text.position, text.color, MathHelper.ToRadians(text.rotation), text.origin, text.scale, text.spriteEffects, text.layer);
}
spriteBatch.End();
I try some way to do this and crate new Object between game. for example I want to crate new bullet when i press space.
But I cant make new GameObject between Game;
Please help me.
Thanks.
Update :
I trying to add another game object while the game is running;
and the Game.gameObjects is a static list in Game1(I change Game1 name to Game)
and it's on GameObject class :
public GameObject(Sprite sprite)
{
this.sprite = sprite;
rectWidth = (int)sprite.texture.Width;
rectHeight = (int)sprite.texture.Height;
rect = new Rectangle((int)position.X, (int)position.Y, rectWidth, rectHeight);
Game.gameObjects.Add(this);
}
so I can get my GameObjects in game to render they or mange they;
then i have gameObjects is a list and it have All gameObjects in game

Your trying to add another game object while the game is running? Sorry your question is unclear.
I dont know if your Game.gameObjects is an array or list (Could you post the class, and where you initialize it?)
Game.gameObjects.Add(new GameObject(Sprite, position, whatever));
That possibly?

Related

Unity Card Game Change Player Perspective

I am new to C# and Unity.. I am trying to make a simple trading card game (tcg/ccg). For this first phase, I would like to make it to be played locally eg. own-self versus own-self. Would like to know how do we usually do for changing the perspective?
Eg: From the Player1's perspective as below image, once I ended my turn and pass it to player2, I would like to make it remain the same view but by showing player2's Hand card and Field card (also at the same time hide the Player1 hand card).
Below is just part of my code :
UiController.cs
[Header("General")]
[SerializeField] private GameObject BattleCardPrefab;
[Header("Player Detail")]
[SerializeField] private GameObject PlayerDeck;
[SerializeField] private GameObject PlayerHand;
[Header("Enemy Detail")]
[SerializeField] private GameObject EnemyDeck;
[SerializeField] private GameObject EnemyHand;
private void GetUserObject(int _player)
{
UserDeck = _player == 0 ? PlayerDeck.transform : EnemyDeck.transform;
UserHand = _player == 0 ? PlayerHand.transform : EnemyHand.transform;
}
public void InitDeck(int _player, List<Card> _deck)
{
foreach (var card in _deck)
{
GameObject resultCards = Instantiate(BattleCardPrefab, UserDeck);
resultCards.GetComponent<CardDetail>().card = card;
resultCards.GetComponent<CardDetail>().ShowCardBack(_player, resultCards, 0);
}
}
Player.cs
public Player(int _playerIndex, string _deckName)
{
playerIndex = _playerIndex;
deckName = _deckName;
}
public void GameStartSetUp(string _deckName){
//initDeck and extra
//blablabla
}
BattleManager.cs
Player player = new Player(0, "testdeck1");
Player enemy = new Player(1, "testdeck2");
void Start()
{
StartGame();
}
public void StartGame()
{
player.GameStartSetUp();
enemy.GameStartSetUp();
}
Please let me know if need more information from my side, mercy and thanks!
Scene Setup
Create 2 empty game objects, "Player 1 Main View" and "Player 2 Main View".
Use the following steps for both objects:
Parent your camera to the object and zero out the cameras position and rotation.
Move that object (with the camera as child) to where the camera should be.
Rotate the object so the camera view looks correct.
Unparent the camera.
Repeat for other views.
Code
From code we parent the camera to the appropriate view object and zero out the cameras local position and local rotation.
public Camera viewingCamera; // <- assign your camera in inspector
public Transform player1MainView; // <- assign "Player 1 Main View" object in inspector
public Transform player2MainView; // <- assign "Player 2 Main View" object in inspector
public void EnablePlayer1View()
{
EnableView(player1MainView);
// Hide player 2 canvas, flip over cards, etc.
// Show player 1 canvas, show cards, etc.
}
public void EnablePlayer2View()
{
EnableView(player2MainView);
// Hide player 1 canvas, flip over cards, etc.
// Show player 2 canvas, show cards, etc.
}
private void EnableView(Transform viewObject)
{
viewingCamera.transform.SetParent(viewObject);
viewingCamera.transform.localPosition = Vector3.zero;
viewingCamera.transform.localRotation = Quaternion.identity;
}
To switch the view to "Player 1", call EnablePlayer1View(). For "Player 2" call EnablePlayer2View().

Unity destroying player outside of boundary box (Saving positions in a for loop)

I would like some help with figuring this out as my brain is having a funny day today at what is the best way to go about this.
I have an OnDrawGizmos as follows
Transform parentBounds;
void OnDrawGizmos()
{
parentBounds = this.gameObject.transform;
Vector3 from;
Vector3 to;
for (int a = 0; a < parentBounds.childCount; a++)
{
from = parentBounds.GetChild(a).position;
to = parentBounds.GetChild((a + 1) % parentBounds.childCount).position;
Gizmos.color = new Color(1, 0, 0);
Gizmos.DrawLine(from, to);
}
}
This code is attached on a "parent" object which contains 4 empty game objects as follows
Which produces the following Gizmo (Drawing a square based on where I put the empty objects within the parent)
I can even add more points if I desire.
SO WHAT IS THE PROBLEM ?
What I need is that if the player is not within this box area, I want the player to be destroyed. I'm not sure what the best practice is for this , should I make an array to hold the xmin, ymax, etc. ? or should I generate a new position vector on every loop ? I've tried a few ways that are not giving me the results I want and I taught to ask for some assistance.
Thank you all in advance !
If this is a 2D game (which I assume it is), how about having a script, that has reference to the player object and...
a) game is not using physics
... a public Rect boundaries. On each Update() check if player is within the boundaries and if not - destroy it.
void Update()
{
if (!boundaries.Contains(playerObject.transform.position))
{
Destroy(playerObject);
}
}
b) game is using physics
... a BoxCollider2D with the following script
void OnColliderExit2D(Collider2D collider)
{
// If collider is player object -> destroy collider.gameObject
}

Unity Editor Pipeline Scripting: how to Pass Sprite to SpriteRenderer in OnPostprocessSprites() Event?

after importing sprites inside unity , i want to make a Prefab out Of them and assign them a SpriteRenderer and BoxCollider2D component , all automaticly.
every thing is good exept i cant pass the imported Sprite to the SpriteRenderer component any how.
i dont knoow what im missing here. any help will be appritiated.
void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
{
Sprite sp = sprites[0];
TextureImporter importer = (TextureImporter)assetImporter;
importer.textureType = TextureImporterType.Sprite;
GameObject GO = new GameObject();
GO.name = sp.name;
string ResAddress = importer.assetPath.Remove(importer.assetPath.Length - 4, 4).Replace("Assets/Resources/", "");
Debug.Log("Resource Address = " + ResAddress);// Images/Objects/car acceptable for Resource.load
//GO.AddComponent<SpriteRenderer>().sprite = sp;// not works
GO.AddComponent<SpriteRenderer>().sprite = (Sprite)Resources.Load(ResAddress);// not works
GO.AddComponent<BoxCollider2D>();
Object prefab = PrefabUtility.CreateEmptyPrefab(string.Format("Assets/Resources/X_Temp/{0}.prefab", GO.name));
if (prefab != null)PrefabUtility.ReplacePrefab(GO, prefab, ReplacePrefabOptions.ConnectToPrefab);
}
there is no Error or messages , it makes the prefab with BoxCollider And SpriteRendere Components But SpriteRenderer's Sprite Field Has No Sprite, and set to none or Missing.
how can i fix this?
also asked in Unity Community And No luck.
https://answers.unity.com/questions/1434068/how-to-pass-sprite-to-spriterenderer-in-onpostproc.html
https://forum.unity.com/threads/how-to-pass-sprite-to-spriterenderer-in-onpostprocesssprites-event.505638/
====== UPDATE And NOT RECOMMENDED ANSWER ======
void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
{
TextureImporter importer = (TextureImporter)assetImporter;
if (AssetDatabase.LoadAssetAtPath<Sprite>(importer.assetPath)==null)
{
AssetDatabase.Refresh();
return;
}
foreach (Sprite sp in sprites)
{
importer.textureType = TextureImporterType.Sprite;
GameObject GO = new GameObject();
GO.name = sp.name;
Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(importer.assetPath);
GO.AddComponent<SpriteRenderer>().sprite = sprite;
string address = string.Format("Assets/Resources/Prefabs/{0}.prefab", GO.name);
PrefabUtility.CreatePrefab(address, GO);
PrefabUtility.ReconnectToLastPrefab(GO);
}
}
not recommended Because Of the following Crash Error :
A default asset was created for 'Assets/Resources/Images/Objects/car.png' because the asset importer crashed on it last time.You can select the asset and use the 'Assets -> Reimport' menu command to try importing it again, or you can replace the asset and it will auto import again.UnityEditor.AssetDatabase:Refresh()
This is really interesting. I don't think that Resources.Load(ResAddress) is returning null otherwise you should see null if you use Debug.Log on it. I assumed that the texture variable from the OnPostprocessSprites function would work if you convert it to Sprite then assign it to the SpriteRenderer like so:
Sprite tempSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
GO.AddComponent<SpriteRenderer>().sprite = tempSprite;
That didn't work too despite the fact that tempSprite is not null. This quickly made me remember the AssetDatabase API which is specifically used to access and operate on assets.
You are looking for the AssetDatabase.LoadAssetAtPath function. It will return the proper Sprite asset you can use to change the SpriteRenderer.sprite property.
This should work:
Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
GO.AddComponent<SpriteRenderer>().sprite = tempSprite;
It would make sense to call AssetDatabase.Refresh() after all these but it seems to work without calling AssetDatabase.Refresh(). I still think you should call it.

Create material from code and assign it to an object

I am very new to Unity3d. I have a prefab which contains 6 quads making it a cube. I want to add image textures to different faces of cube.
I am getting images from a web service, so I have to add or change material in the script.
The problem I am facing is, I am not able to find material property in gameObject.
I have tried below code:
using UnityEngine;
using System.Collections;
public class shelfRuntime : MonoBehaviour {
public GameObject bottle;
public GameObject newBottle;
// Use this for initialization
void Start () {
iterateChildren(newBottle.transform.root);
GameObject rocketClone = (GameObject)Instantiate(bottle, bottle.transform.position, bottle.transform.rotation);
rocketClone.transform.localScale += new Vector3(1, 1, 1);
GameObject newBottleInMaking = (GameObject)Instantiate(newBottle, newBottle.transform.position, newBottle.transform.rotation);
Transform[] allChildren = newBottleInMaking.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
// do whatever with child transform here
}
}
void iterateChildren(Transform trans)
{
Debug.Log(trans.name);
if (trans.name == "Back") {
var ting = trans.gameObject.GetComponent<Renderer>();
// trans.renderer.material // there is no material property here
}
// Do whatever logic you want on child objects here
if (trans.childCount == 0) return;
foreach (Transform tran in trans)
{
iterateChildren(tran);
}
}
// Update is called once per frame
void Update () {
}
}
How to set material to quads? There are 6 quads inside my prefab.
You can no longer access some components directly in Unity. You must use GetComponent to get the component(Renderer) then access the material from it.
trans.renderer.material = ....
should be changed to
trans.GetComponent<Renderer>().material = yourNewMaterial;
Finally, when Cube or Quad is created in Unity, MeshRenderer is automtatically attached to them not Renderer. So, you might get run-time error with GetComponent<Renderer>(). Use MeshRenderer instead.
trans.GetComponent<MeshRenderer>().material = yourNewMaterial;
To create Material during run-time:
Material myNewMaterial = new Material(Shader.Find("Standard"));
The example below will create a Material, assign standard shader to it then change the texture to the texture from the myTexture variable before applying it to a GameObject.
public Texture myTexture;
void Start()
{
//Find the Standard Shader
Material myNewMaterial = new Material(Shader.Find("Standard"));
//Set Texture on the material
myNewMaterial.SetTexture("_MainTex", myTexture);
//Apply to GameObject
trans.GetComponent<MeshRenderer>().material = myNewMaterial;
}

Unity: avatar creation

I'm making my own avatar builder in Unity and I'm stuck on a few key bits I need to implement.
Right now I have taken the avatar that Unity provide with its Mechanim tutorial and I've gave the hat a tag and have instantiated an object at that location. This point is simply an empty game object attached as a child to the head of the model. However I'm having issues making the newly spawned object move and stay with the head as the animation plays. When the avatar moves, the hat just stays in one static position.
How can I make it so that the hat stays with the players head and moves and rotates as the animation is rotating?
My code is really simple as I've no prior experience trying do what I'm doing so even if someone could point me in the right direction on how to build an avatar creator in Unity, I'd appreciate it.
My code as it stands:
public GameObject equipItem;
public GameObject hat;
// Use this for initialization
void Start ()
{
hat = GameObject.FindGameObjectWithTag("Hat");
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
if(GUI.Button(new Rect(0,0, 100, 50), "Equip Item"))
{
SpawnWeapon();
}
}
void SpawnWeapon()
{
Instantiate(equipItem, hat.transform.position, hat.transform.rotation);
}
What you are missing is making the new object a child to the object you want it to follow. This can be done in the transform of the new object
void SpawnWeapon()
{
GameObject newObject = Instantiate(equipItem, hat.transform.position, hat.transform.rotation) as GameObject;
newObject.transform.parent = hat.transform;
}
this is the same a dragging the new object onto the other object in the inspectors hierarchy window and thus causing it to inherit all transformations made to the parent

Categories