I'm having trouble putting 3 values in line 16 - c#

I need help converting the variable "r" to a float.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Calculate : MonoBehaviour
{
double pi = 3.14159;
public InputField r;
public Text circumference;
public Text area;
public void calculate()
{
circumference.text = ("Circumference = " + 2 * pi * r);
}
}
I have tried using the TryParse method and Parse Method, They don't work or i'm not using them correctly.
I left the code how I originally coded it.
If you can fix this please reply with an answer.

What did happen when you used parse?
This following example does what you want.
Note the CultureInfo.InvariantCulture in the conversion from and to string. It prevents conversion between . and , that could happen depending on your locale.
I'd recommend you use longer variable names for clarity in the future but of course that is up to you.
using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public class CalculateCircle : MonoBehaviour
{
private double pi = 3.14159;
public InputField r;
public Text circumference;
public Text area;
private void Start()
{
r.onEndEdit.AddListener(delegate { Calculate(); });
}
public void Calculate()
{
float radius = 0;
try
{
radius = float.Parse(r.text);
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
double circumferenceValue = 2 * pi * radius;
double areaValue = pi * radius * radius;
circumference.text = circumferenceValue.ToString(CultureInfo.InvariantCulture);
area.text = areaValue.ToString(CultureInfo.InvariantCulture);
}
}

float rF = float.Parse(r.text);
Remember about error handling, and making sure the input is always a float. Otherwise, use TryParse.

Related

"itemSlotRectTransform" is a variable but is used like a type?

I'm following a tutorial to make an inventory (this one to be exact link to video)
a line in the code goes as follows:
RectTransform itemSlotRectTransform = Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<itemSlotRectTransform>();
i get the error
"itemSlotRectTransform" is a variable
but is used like a type.
nobody else seems to get this error.
For reference, here is the full bloc of code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InventoryUI : MonoBehaviour
{
private Inventory inventory;
private Transform itemSlotContainer;
private Transform itemSlotTemplate;
private void Awake()
{
itemSlotContainer = transform.Find("itemSlotContainer");
itemSlotTemplate = transform.Find("itemSlotTemplate");
}
public void SetInventory(Inventory inventory)
{
this.inventory = inventory;
RefreshInventoryItems();
}
private void RefreshInventoryItems()
{
int x = 0;
int y = 0;
float itemSlotCellSize = 30f;
foreach (Item item in inventory.GetItemList())
{
RectTransform itemSlotRectTransform =
Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<itemSlotRectTransform>();
itemSlotRectTransform.gameObject.SetActive(true);
itemSlotRectTransform.anchoredPosition =
new Vector2(x * itemSlotCellSize, y * itemSlotCellSize);
x++;
if(x > 4)
{
x = 0;
y++;
}
}
}
}
if you could help I'd much appreciate!
Generic arguments must be types whereas you specified an instance of a type.
Try this instead:
Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<RectTransform>()
Notice the argument in angle brackets.

the script don't inherit a native class that can manage a script unity

I'm a beginner programmer on c# and Unity.
So I was making a grid system for my game and when I'm trying to add as a component every script in my unity project it prints this one error : "The script don't inherit a native class that can manage a script"
I don't know what i need to do.Help me please if u can
//////////first script///////////////
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gird1 : MonoBehaviour
{
private int width;
private int height;
private int[,] gridArray;
public Gird(int width, int height)
{
this.width = width;
this.height = height;
gridArray = new int[width, height];
Debug.Log(width + " " + height);
}
}
////////second script////////////////////
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Testing : MonoBehaviour
{
private void Start()
{
Grid grid = new Grid(20, 10);
}
void Update()
{
}
}
image of grid
Your first script is named "Gird" not "Grid".
Second Script:
public class Testing : MonoBehaviour
{
public Gird1 gird1; // Assign in the inspector. We need an instance of Gird1
private void Start()
{
if (gird1 == null) { // In case someone forgot to assign in the inspector
gird1 = (Gird1)FindObjectOfType(typeof(Gird1)); // .. We'll search the scene
}
gird1.Gird(20,10); // Call the Gird() function on your gird1 instance
}
}

Can't figure out how to access an int from another script

I know this question has been asked before, here and here.
But I still can't get variables from another script. I don't know what I'm doing wrong.
*(I'm really new to programming in general so I might have missed something glaringly obvious)
I keep on getting the error: The name 'points' does not exist in the current context
The slimespawner script is on the Canvas.
Sorry if the question is too simple.
here's the script I'm trying to access:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class slimespawner : MonoBehaviour
{
public int points;
public Text score;
public float xx;
public float yy;
void Start()
{
points = 0;
xx = Random.Range(-32f, 32f);
yy = Random.Range(-18.5f, 18.5f);
}
void Update()
{
score.text = "Score: " + points.ToString();
}
}
And here's the script that's trying to use the points variable.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class slimecontroller : MonoBehaviour
{
private float movespeed = 0.1f;
public slimespawner slisp;
void Start()
{
slisp = GameObject.Find("Canvas").GetComponent<slimespawner>();
}
void Update()
{
points += 1;
}
}
Your code should look as this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class slimecontroller : MonoBehaviour
{
private float movespeed = 0.1f;
public slimespawner slisp;
void Start()
{
slisp = GameObject.Find("Canvas").GetComponent<slimespawner>();
}
void Update()
{
slisp.points += 1;
}
}
Access the property with slisp.points += 1;

how to declare/use a getcomponent variable in Unity3D c#

I have tried many for few hours and am scratching my head on how to get this done.
I need to get a variable from a script and change it by +3
using UnityEngine;
using System.Collections;
public class SwordKillScript : MonoBehaviour {
public GameObject moneyAmount;
private Component MoneyText;
void Awake () {
moneyAmount = GameObject.FindGameObjectWithTag ("Money");
MoneyText = moneyAmount.GetComponent<moneyText> ();
}
void OnCollisionEnter2D (Collision2D collisonInfo){
Debug.Log ("Killed");
if (collisonInfo.collider.tag != "Player") {
MoneyText.money += 3;
Destroy (collisonInfo.collider.gameObject);
}
transform.position = transform.position;
}
}
That is the code for a sword, when it hits an object it destroys it then is supposed to add +3 to this script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class moneyText : MonoBehaviour {
Text txt;
public int money = 20;
void Start () {
txt = gameObject.GetComponent<Text>();
txt.text= "$: " + money;
}
}
any help is great, I hope that this question is easy to read and answer.
Please answer as simply as possible and give the reason why, I will end up doing this sort of thing many times over and would love to know.
Thankyou!
BTW: Expect errors, I need to know what I can do to make this work - Thanks again.
EDIT: Here is the code I am having more trouble with, i've fiddled with assigning everything from strings to getcomponent, HALP!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MoneyText : MonoBehaviour {
public GUIText txt;
public int money = 20;
public void ModifyMoney () {
money += 3;
txt.text = "$: " + money;
}
}
There's nothing wrong in your script. You're getting the component correctly, and also incrementing the value correctly. The reason you're probably not seeing the updated value is because you set the value of the text only once in the Start() function.
i.e. txt.text= "$: " + money;
There's many ways of updating the text. You could do any of the following
A) Make the txt variable in moneyText public. Then in your SwordKillScript, you can add the following line
MoneyText.money += 3; //You have this already
moneyAmount.txt.text = "$: "+MoneyText.money; //Add this line
B) Write a method in the moneyText class which modifies the value of money.
public void ModifyMoney (int howMuch) {
money += howMuch;
txt.text = "$: "+money;
}
Call this method from SwordKillScript
C) You can make money a property.
private int money = 20;
public int Money {
get { return money; }
set {
money = value;
txt.text = "$ : "+money;
}
}
Then, in SwordKillScript, you just need to increment Money
P.S. Your naming conventions are a little off. Might I suggest that you take a look at it? Class names, for example, begin with an uppercase (MoneyText instead of moneyText)

How to call a method into a constructor in the same class and pass user input into this?

I found few posts on here quite similar to my question. But that's not helping. I want to calculate area of a circle. Rather than passing value by myself I want to take user input hence I created a method called myValue(). Now I want to call that method or int _radius variable into a constructor. I am new to C# and like your advice on this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticeFor70_483Exam.Venkat
{
class Circle
{
private readonly int Radius;
public static int MyValue()
{
Console.WriteLine("Please enter radius value: ");
return Convert.ToInt32(Console.ReadLine());
}
float _PI = 3.141F;
public Circle()
{
Radius = myValue();
//this._radius = Radius;
}
public float CalculateArea()
{
return this._PI * this.Radius * this.Radius;
}
}
class StaticAndInstanceClass
{
public static void Main()
{
Circle c1 = new Circle(2);
float Area = c1.CalculateArea();
Console.WriteLine("The area is: {0}", Area);
Console.ReadLine();
}
}
}
Make the radius an instance field of the Circle class and modify the MyValue method.
public class Circle
{
private readonly int Radius;
public static int MyValue()
{
Console.WriteLine("Please enter radius value: ");
return Convert.ToInt32(Console.ReadLine());
}
public Circle()
{
Radius = MyValue();
}
...
}
Please note that this is a very "bad idea" though, your circle class should represent a circle and nothing else. Giving it information about the console is strange to say the least. It violates the Single Responsibility Principle among other things.
You have two problems in the given code:
1. myValue() instead of MyValue(). Since, it is case sensitive.
2. Circle(2) instead of Circle(). Since, it does not have a constructor that takes parameter.

Categories