How can I add objects to a scene via button click in Unity? - unityscript

I would like to know how to use a button click to bring objects to the scene.

1) Create a button using Unity GUI system.
2) Create a script:
public GameObject sampleObject;
public void AddObject()
{
Instantiate(sampleObject, Vector3.zero, Quaternion.Identity);
}
3) Attach this script to an object in the scene, and set a prefab to sampleObject.
4) Select your button and in the Inspector add a new OnClick script, and select the object with the new script attached, select AddObject() method.
Now when you click on the button it should instantiate an object at (0.0f, 0.0f, 0.0f).
Hope that helps you.

I think use gameObject z postion value and show or hide when this object allready created
Find current gameObject and set transform.postion.z = -1 or 1
if gameObject z postion set to -1 hideObject else showObject
sampleCode
float yourChose = -1f; // chose object hide or show (-1 or 1 )
foreach (var item in FindObjectsOfType(typeof(GameObject)) as GameObject[])
{
if (item != null && item.name == "CurrentObjectName")
{
item.transform.position = new Vector3(item.transform.position.x, item.transform.position.y, yourChose);
}
}

Related

Add Image dynamically in runtime - Unity 5

In my unity based Android game I wish to add the image dynamically based on the number of questions in each level. The image is shown for reference. Each correct answer will be marked in green and the wrong one in red. I am new to unity and trying hard to find steps to achieve this.
Any help with an example for this requirement will be a great help.
I once wrote a script for dynamically creating buttons based on each level. What I did was creating the first button on the scene and adding the other buttons based on the first one. Below is the shell of my code:
// tutorialButton and levelButtons are public variables which can be set from Inspector
RectTransform rect = tutorialButton.GetComponent<RectTransform> ();
for (int i = 1; i < levelSize; i++) {
// Instantiate the button dynamically
GameObject newButton = GameObject.Instantiate (tutorialButton);
// Set the parent of the new button (In my case, the parent of tutorialButton)
newButton.transform.SetParent (levelButtons.transform);
//Set the scale to be the same as the tutorialButton
newButton.transform.localScale = tutorialButton.transform.localScale;
//Set the position to the right of the tutorialButton
Vector3 position = tutorialButton.transform.localPosition;
position.x += rect.rect.width*i;
newButton.transform.localPosition = position;
}
I am not exactly sure if this is the right approach as it may or may not give unexpected results depending on different screen sizes and your canvas, but hopefully it gives you an idea about dynamically creating objects.
I'm not sure if this helps, but if you have all the images in the scene under a canvas, with this you just need to drag the canvas on the script and use
//level-1 is to keep the array notation
FindObjectOfType<NameOfScript>.ChangeColor(level-1,Color.green);
or you can do also
//level-1 is to keep the array notation
FindObjectOfType<NameOfScript>.RevertColor(level - 1);
This is the script:
//Keep it private but you still see it in inspector
//#Encapsulation :)
[SerializeField]
private Canvas _canvas;
private Image[] _images;
//keep the original colors in case you want to change back
private Color[] _origColors;
void Start () {
_images = GetComponentsInChildren<Image>();
_origColors = new Color[_images.Length];
for (int i = 0; i < _images.Length; i++)
{
_origColors[i] = _images[i].color;
}
}
//Reverts the color of the image back to the original
public void RevertToOriginal(int imageIndex)
{
_images[imageIndex].color = _origColors[imageIndex];
}
//Change to color to the coresponding index, starts from 0
public void ChangeColor(int imageIndex, Color color)
{
_images[imageIndex].color = color;
}
P.S If you want it visible only at the end you can make a method where you enable = (true or false) for the canvas. So you keep it false till the end of the level and you make it true when you want to show, while after every answer you call the ChangeColor depending on the result.
To make it easier you can use:
NameOfScript variableName = FindObjectOfType<NameOfScript>();
and after that you just call
variableName.ChangeColor(level - 1, Color.green);
Also it does not matter where you put the script. I would make some kind of manager(empty GameObject) in the scene and put it there.

Changing alpha of Text's CanvasGroup in OnTriggerEnter Unity

I'm currently working on a game that pays hommage to Marble Blast Gold/Ultra.
At this point I have text that is positioned with the marble. The text is a child of a canvas and I have a canvas group added to the text. I initially set the alpha of the canvas group to 0 so that you can't see the text.
What I'm trying to do is have it so that when you pick up a power up the text reappears by changing the canvas group's alpha back to 1 and then once the power up is used set it back to 0.
I'm not seeming to have any luck with my current code.
// Super Jump pickup
if (col.gameObject.tag == "Spring")
{
superJumpText.GetComponent<CanvasGroup>().alpha = 1;
canSuperJump = true;
canSuperSpeed = false;
col.gameObject.SetActive(false);
hitSuperJump = true;
Invoke("Display", 20);
}
void Update()
{
//super jump
if (canSuperJump)
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Vector3 jump = new Vector3(0, superJumpForce, 0);
GetComponent<Rigidbody>().AddForce(jump);
canSuperJump = false;
superJumpText.GetComponent<CanvasGroup>().alpha = 0;
}
}
}
The only reason this would not work for you is that somewhere in your parent hierarchy you have a gameobject with another canvas group. That would ALWAYS override the child canvas group settings UNLESS you select the 'Ignore Parent Groups' checkbox in the child canvas

Use parameters for variable animation

I'd like to animate my Score-GUI text counting up to a variable value but there are two things in my way:
1: How can I animate to a variable instead of a fixed value?
2: Why can't I add own properties (like int) to my script and animate them?
For #2 I created a property in my script. Yet the editor won't show it in the AddProperty-dialog (as shown below):
public int currentScore = 0;
public int score {
get { return currentScore; }
set { this.currentScore += value; }
}
EDIT: The animator is set up in the most basic way:
Since you only have 1 Animation. An Animator is irrelevant to the solution. This is tested and working. Now you need to make the Animation a Legacy type to get this working because we are not going to use the Animator.
Click the Animation on the Project -> look at the upper right section of the Inspector view, there is a little button there which will drop down a selection. "Debug" then Check the Legacy.
Set your Animation to whatever you want. I force the WrapMode in the script to be wrap mode once. So it will only play once.
Now in the Animation Component make sure you select the Animation that you want by default or it wont work. Cause we only use anim.Play(); Without parameters meaning, run the default animation that is set.
I created a Text UI and added an Animation that alpha is 0 from the start and at the end point making it 1. You have to do that on your own.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MyScore : MonoBehaviour {
// Use this for initialization
public int currentScore = 0;
public GameObject Myscore; // Drag the GameObject that has the Animation for your score.
public Text myScoreText; //Drag in the Inspector the Text object to reference
public Animation anim;
public int score
{
get { return currentScore; }
set { this.currentScore += value; }
}
void Start()
{
anim = Myscore.GetComponent<Animation>(); // Reference the Animation Component.
anim.wrapMode = WrapMode.Once; // Legacy animation Set to play once
AddScore();
}
public void AddScore()
{
score += 10;
myScoreText.text = score.ToString();
anim.Play();
Debug.Log("Current Score is "+ score);
Invoke("AddScore", 2);
}
}
Good luck.

How do I get the screen or window coordinates of CTreeCtrl node?

I want to generate a context menu but I need to know where to put it, so I need the coordinates of the node currently selected.
Use CTreeCtrl::GetItemRect(). This will state the rectangle of the tree node.
You can use 'GetCursorPos' and'HitTest method in treeclick event for displaying context menu as below.
//here i am asuming that you want to display menu on mouse rightclick
void MyDialog::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult)
{
CPoint CurPos;
GetCursorPos(&CurPos);
CPoint CurP=CurPos;
m_pwTree.ScreenToClient(&CurPos);// m_pwTree is object of CTreeCtrl class
UINT nFlags;
HTREEITEM htItem = m_pwTree.HitTest(CurPos, &nFlags);
if (htItem != NULL ) {
CMenu menu;
CMenu* pContextMenu;
menu.LoadMenu(IDR_MyMenu)//load appropriate menu
pContextMenu=menu.GetSubMenu(0); pContextMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON,CurP.x,CurP.y,this,0);
}
}

Qt- How to Draw Text from a QListWidget

Am Learning to do something with QListWidget. I have a QListWidget, QTextEdit , 2 QPushButtons (Add & Remove Buttons) and a QWidget for drawing the Text in it. When i enter a text in the QTextEdit and Click's the Add Button, the text has to add in the QListWidget. And from that QListWidget, i select any item and click's the Remove Button, the item has to be removed from the QListWidget. Then i want to draw this QListWidget Items in the QWidget and this drawed items has to scroll from Right to left. How can i do this? Plz help me...
//In the constructor
WidgetString = "";
On_add_button_Clicked() //SLOT
{
listwidget->addItem(lineedit->text());
}
On_Remove_Button_clicked() //SLOT
{
listWidget->takeItem(listWidget->currentIndex());
//You may have to delete the the item taken in order to put that change into effect.
//Trigger paintevent
}
on_listWidget_currentTextChanged(QString currentText) //SLOT
{
WidgetString = currentText;
}
paintevent()
{
QPainter painter(Your_Qwidget);
painter.drawText ( int xPos, int YPos, WidgetString )
update();
}
For the Scrollbar thing, you may need to increase the Text size you are going to Draw.

Resources