#💻┃code-beginner
1 messages · Page 308 of 1
Active doesn't necessarily mean visible but not greyed out.
it is greyed out
Are you setting it inactive anywhere?
Does anybody know how to animate enemies in 8 directions (2d) using A* pathfinding? I've basically made a clone of my player animations and changed it from "input values" to calculate the transform - last position in hopes that it will work, but I honestly am over my head lmao
Debug.Log($"VaultUI is active in hierarchy - {vaultUI.activeInHierarchy}", vaultUI); is what you should test
i did the important stuff, idk if thats the issue i dont think so tho, u put the kill script on the canvas
{
public int DMG = 1;
public int Coins = 0;
public TMP_Text CoinCounter;
public Slider SlimeHealth;
bool isDead = false;
public void DmgSlime()
{
SlimeHealth.value =- DMG;
if (SlimeHealth.value == 0)
{
isDead = true;
}
}
public void AddMoney()
{
if (isDead == true)
{
Coins++;
CoinCounter.text = Coins.ToString ();
SlimeHealth.value = 5;
}
}
}```
theres the code too
@ivory bobcat do you mind if I put my problem in a thread to better communicate? its getting kinda complicated imo
i'll try that, give me a sec tho
hm interesting, so theres a bug with the dmg output
i put it at 1 but it does infinite
and i think that causes the other stuff to break
oh nvm
the issue with the add money void i dont have a proper way to call on it
The term is method not void
sorry
is there a chance u might know whats the reason of the dmg output being infinite?
i tried a huge number and it deplets it all
ive looked into that but idk i couldnt figure it out
there have several suggestoins for solutions now that ive become lost.
when i watched a interface tutorial it seemed to be pretty fitting for what im trying to do but idk
-= not =-
VaultUI is active in hierarchy - True
UnityEngine.Debug:Log (object,UnityEngine.Object)
vaultTip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/Script/vaultTip.cs:26)
now im going to look for a way to call on my AddMoney Method
ill look up a quick tutorial about this and see
or do you think i should put everything in the dmg slime method? it should work but i believe it would be a bad way to do it
your code, your design
what
thats the thing i dont know how to call it thru my code
you mean call a method?
yes
so you'd use GetComponent<Thing>()right?
why would calling one method, which you obviously do be any different than calling a different one?
you should seriously go through the beginner c# courses pinned in this channel
i am calling DmgSlime everytime the slime is being used
but once the health reaches 0 i would like to call on the Addmoney Void to reset the health and 1 one coin
if you do that, you'll probably learn how to call a method, and when you learn how to do that you might realize that you can just call the method instead of using that useless bool
yep i have realized that
cool. now go learn the basics
public void DmgSlime()
{
SlimeHealth.value =- DMG;
if (SlimeHealth.value == 0)
{
AddMoney(); // call a function from within another function
}
}```
its that simple?
you just use the name of the void?
sorry method
learn the basics
most every tutorial will cover that
i just made my first game with a little of help
idk if thats considred impressive here
@strong wren Use the thread #💻┃code-beginner message
Hello everyone, I have a problem. When I call an if block inside fixedupdate it works as I want, but it reduces FPS a lot. I want to write this in Coroutine, but this time if blocks do not work. For this reason, when I open as many coroutines as if blocks and rotate them in another coroutine, I feel like I'm doing something very stupid, and although it doesn't reduce the fps as much as the fixedupdate function, it reduces it a lot. How can I revise this code? Can you help me?
private void FixedUpdate()
{
if (TotemKoruyanlar[0].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF0)
{
DirilmeTF0 = true;
}
if (TotemKoruyanlar[1].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF1)
{
DirilmeTF1 = true;
}
if (TotemKoruyanlar[2].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF2)
{
DirilmeTF2 = true;
}
if (TotemKoruyanlar[3].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF3)
{
DirilmeTF3 = true;
}
if (TotemKoruyanlar[4].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF4)
{
DirilmeTF4 = true;
}
if (TotemKoruyanlar[5].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF5)
{
DirilmeTF5 = true;
}
if (TotemKoruyanlar[6].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF6)
{
DirilmeTF6 = true;
}
}
IEnumerator TotemTakasDongu2Cor()
{
yield return YarimSaniyeBekleme;
if (TotemKoruyanlar[0].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF0)
{
DirilmeTF0 = true;
}
if (TotemKoruyanlar[1].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF1)
{
DirilmeTF1 = true;
}
if (TotemKoruyanlar[2].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF2)
{
DirilmeTF2 = true;
}
if (TotemKoruyanlar[3].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF3)
{
DirilmeTF3 = true;
}
if (TotemKoruyanlar[4].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF4)
{
DirilmeTF4 = true;
}
if (TotemKoruyanlar[5].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF5)
{
DirilmeTF5 = true;
}
if (TotemKoruyanlar[6].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF6)
{
DirilmeTF6 = true;
}
StartCoroutine(TotemTakasDongu2Cor());
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i need help with a small game of mine
The PROBLEM here is that the bullets are not depleting. ik why they are not but idk how to solve it.
GUN / SHOOTING SCRIPT : https://pastebin.com/TDqsRDpq
WEAPON SWITCHING SCRIPT: https://pastebin.com/1afDWMc6
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
My goal is to ensure that the values I want are true when the if condition is met.
to start with please put your DirilmeTF variables into an array and make a loop of the code
yeh
so i used a new function
that will detect when the weapon is switched and will change the magazine size accordingly
but i had to use it in update
and thats why whenever the i change the weapon, the if statements are always true and thus infinite ammo
There are 3 different code types. I wrote the explanation in my message above.
if(changeWeapon.isPistolStc){
clipSize = 10f;
}
}
void changeRifleClip(){
if(!changeWeapon.isPistolStc){
clipSize = 20f;
}
}```
``` void Update()
{
changePistolClip();
changeRifleClip();
if(Input.GetKeyDown(KeyCode.R)){
clipSize = fullClipSize;
noAmmo = false;
rifleDMG = 20f;
pistolDMG = 10f;
}
}
the problems are here
Ok I will do it and come back
idk what the solution can be
hey, I want an 16x16x16 byte structure, so I declared a ushort[16][], the idea being that each byte is already 16 bits, and I want an 16x16 of bytes. I have 2 concerns:
- it doesn't let me specify that the second dimension of the array should also be 16
- can I perform bitwise operations on this structure?
to first
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/arrays#multidimensional-arrays
to second
you can perform bitwise operation on single element only
i need help plsssss
here is the problem
thanks
private void FixedUpdate()
{
for(int i = 0; i < 7; i++)
{
if (TotemKoruyanlar[i].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF[i])
{
DirilmeTF[i] = true;
}
}
} Thisi is work
but this don't work
IEnumerator TotemTakasDongu2Cor()
{
yield return YarimSaniyeBekleme;
for (int i = 0; i < 7; i++)
{
if (TotemKoruyanlar[i].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF[i])
{
DirilmeTF[i] = true;
}
}
StartCoroutine(TotemTakasDongu2Cor());
}
why
Can you revise the coroutine?
can I overload bit operations if uint[16,16] isn't technically a custom type?
Why isn't this Coroutine working the way I want it to? Can someone who knows revise it and correct me if I'm wrong?
define 'don't work', that is not a very helpful comment
no
you can't directly overload operators for built-in types such as uint
unless you make some kind of wrapper for it
When I write into FixedUpdate when there is an enemy, the tick works, but when I write into the Coroutine, the if blocks work and do not activate the tick. What am I doing wrong with the Coroutine? Can someone who understands Coroutine revise this code?
So how and where do you start the coroutine
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yes, what's wrong with this code?
You should read the bot message that came up
it tells you how to post code
I also called it inside the start function, but I'm doing something wrong, I don't know where.
Ok
so show that code
would that be something like this?
obviously not exactly
No, you don't inherit from it
is uint a class?
You just have a variable with the type
https://paste.ofcode.org/TdUccz4ghbCESvYErXnG9D This is code
so I just have code with a uint as a variable in it and define the overload on the class instead of the uint?
I dunno what your goal is. You just cannot inherit from it
https://paste.ofcode.org/TdUccz4ghbCESvYErXnG9D this is code
No need to post it twice
Also, you should generally share the WHOLE script
the goal is to overload bitshift operators for a 2d uint array
make a wrapper to contain the whole 2d array
or struct
struct sounds like it'd be better
public struct Wrapper{
Type theActualData;
}
My goal is to create a loop with coroutine and refresh it every 0.5f seconds. Thus, it will not reduce the fps as much as in fixedupdate.
My goal is to create a loop with coroutine and refresh it every 0.5f seconds. Thus, it will not reduce the fps as much as in fixedupdate.
https://paste.ofcode.org/cYyay78xXvVMdQbUaAkvCh Here it also appears in seconds
Again, no need to repeat yourself. If you want to ping multiple people, use the @ sign
@atomic yew
Also, you should share your whole code
ok, so you do not need the StartCoroutine in the Coroutine, wrap the code in a while (true) loop
Also you should cache the GetComponents
Can you show me how to write it? Isn't the while loop too tiring?
Seriously?
IEnumerator TotemTakasDongu2Cor()
{
while (true) {
yield return YarimSaniyeBekleme;
for (int i = 0; i < 7; i++)
{
if (TotemKoruyanlar[i].GetComponent<MaviDusmanlarScript>().DusmanM.hayvancan <= 0 && !DirilmeTF[i])
{
DirilmeTF[i] = true;
}
}
}
}
And cache the GetComponents
Ok i will try it and i will write you
How can I get a float to count up from 0.00 to the value of a variable smooth over a period of time?
I am keeping track of a players score using a float and at the end of the level I want to have the score shown starting at 0.00 then start counting up to the value of the variable and I'm adding a star rating at certain score values
The same didn't work again. I'm already doing almost the same thing with StartCoroutine. I turn the loop again.
you still have not explained what 'didn't work' means to you, we are not mind readers
also what is this
yield return YarimSaniyeBekleme;
supposed to do?
to My question?
i'd just use DOTween
or Lerp
would be easier if you would write your code in english, especially if you want to share it in a english server
I made a game, there are animal mobs and enemy soldiers in the game. When soldiers die, I record this so that they do not immediately revive when the player enters and exits, but when their time is up. I want to keep memory of whether he died or not at the ResurrectionTF value. I can already keep it in memory, but when a character dies in FixedUpdate, ResurrectionTF becomes true. I cannot do it in Coroutine. I want to do this because Coroutine also reduces FPS. Could you look at the screenshot? The soldier died, but the Inspector also did not ResurrectTF true.
private WaitForSeconds YarimSaniyeBekleme = new WaitForSeconds(0.5f);
You are right
You're right, but the game is almost over, I can't do it anymore even if I ask him to. It will take me a week to do what you said.
I cannot see how you setting a variable in an array could possibly affect the inspector
tried mathf.lerp didn't work , nor does mathf.movetwards
it does work, you implemented it incorrectly
just use dotween, it'd be easier and with more control
endOfLevelCorrectPercentageDisplay.text = $"Final Score - {Mathf.MoveTowards(0.00f, correctPercentage, transitionDuration * Time.deltaTime)}";
where is this even called at?
DOVirtual.Float(0, correctPercentage, transitionDuration, f => endOfLevelCorrectPercentageDisplay.text = $"Final Score - {f}");
what's DOVirtual? do i need a namespace
DOTween asset
this one?
yup
then watch this @frail star https://www.youtube.com/watch?v=Y8cv-rF5j6c
DOTween is the very first thing I install upon creating a new project. Animate your position, rotation and scale in a single line of code, with all the customization you could hope for... and that's only scratching the surface.
For the full documentation: http://dotween.demigiant.com/documentation.php
❤️ Become a Tarobro on Patreon: https://ww...
Did i cook?
every spawner rn is like:
public class FireballSpawner : MonoBehaviour, ISpawner
and i have this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseSpawner : MonoBehaviour
{
public interface ISpawner
{
void Spawn();
}
}
Yes that would be the way to do that
i feel like almost all (not sure if all) of them still spawn at the same time, but i assume that just a matter of rng if the code looks fine
Hi. I have a question: Which option would be better or does it make no difference?
Makes no difference, but bottom one can be a bit easier to comprehend
And takes less typing
All about s p e e d
Ok. Thanks
I had a choice: I have 2 choices: make 1 variable: "GameObject" or make several variables, but already by components. What is the best choice and will it affect performance, etc.?
There is basically no reason to have a variable of type GameObject. You should use the type you actually want from it
Thanks
I have the below script attached to the Object in the picture and when i click on the space bar i want it to call the Jump() Function via the Input Action
public class Player : MonoBehaviour
{
public float speed = 3f;
public float JumpForce = 11f;
bool Grounded = true;
Animator anim;
public SpriteRenderer sr;
Rigidbody2D rb;
Transform trans;
public InputAction playerControls;
Vector2 MoveDirection = Vector2.zero;
private void OnEnable(){
playerControls.Enable();
}
private void OnDisable(){
playerControls.Disable();
}
void Awake()
{
anim = GetComponent<Animator>();
sr = GetComponent<SpriteRenderer>();
rb = GetComponent<Rigidbody2D>();
trans = GetComponent<Transform>();
}
void Start()
{
}
void FixedUpdate(){
}
void Update()
{
Player_Jump();
Player_Movement();
Player_Animation();
}
void Player_Movement(){
MoveDirection = playerControls.ReadValue<Vector2>();
Vector3 dir = new Vector3(MoveDirection.x, 0, 0);
transform.position += dir * Time.deltaTime * speed;
}
void Player_Animation(){
float h = Input.GetAxisRaw("Horizontal");
if (h == -1){
anim.SetBool("Walk", true);
sr.flipX = true;
}
else if (h == 1){
anim.SetBool("Walk", true);
sr.flipX = false;
}
else if (h == 0){
anim.SetBool("Walk", false);
}
}
void Player_Jump(){
if (Input.GetButtonUp("Jump") && Grounded){
Grounded=false;
rb.AddForce(new Vector2(0,JumpForce), ForceMode2D.Impulse);
}
}
public void Jump(){
if(Grounded){
Grounded=false;
rb.AddForce(new Vector2(0,JumpForce), ForceMode2D.Impulse);
}
}
}
I'm trying to add a custom script to draw a radius for me, script derives from editor.
When adding to a gameobject I get an error to say it needs to derive from monobehaviour. Any ideas?
If it derives from Editor then it is not a component
and you can't attach it to a GameObject
The error is pretty clear. Which part was confusing about it?
Unhelpful
Well, I am genuinely asking so I can make the issue clear to you
Maybe you didn't understand what a MonoBehaviour was? I dunno, we have people at all stages of their path
on https://docs.unity3d.com/ScriptReference/Editor.html~
They say "You can attach the Editor to a custom component by using the CustomEditor attribute." Which I have done but still getting error for some reason
Show code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
So skeletonSpawner is what you should be adding to the inspector
Looks like you're only modifying OnSceneGUI so it'd change how an object with a skeletonSpawner is shown in the scene view
So select an object with skeletonSpawner and see if you see your custom gizmo in the scene view
I see, it has worked but I was zoomed in further than the radius, I assumed it needed to be on the object to display the wire. Thank you all!
Hello all. I'm developing a two-player game using Relay and NGO. Is there a way I can make the opposing player appear at one part of the screen. A good example is how airhockey works. A player is limited to their half of the screen. So I want that kind of mechanism. Where the opponent appears on the upper half for both players.
that has nothing to do with multiplayer per se.
I have a script running this to collect user input to TMP_InputField in the input field:
[SerializeField]
private string password;
public void grabPW(string input) {
password = input;
}
but the password doesnt store the input. any fixes?
ps: it worked before... i just dont know what i couldve changed to make it not work ..
Your password should store the input, as it's assigned correctly
If your password isn't changed, consider checking whether the grabPW method is called and input isn't the same as the previous password value
have you verified that method is being called
make sure the method is called and log the output of both variables . . .
Debug.Log("The password is " + password); i used this to debug (not sure if good enough)
output was
The password is
UnityEngine.Debug:Log (object)
vaultMech:grabPW (string) (at Assets/Script/vaultMech.cs:19)
UnityEngine.Events.UnityEvent`1<string>:Invoke (string)
TMPro.TMP_InputField:SendOnEndEdit () (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:3149)
TMPro.TMP_InputField:ReleaseSelection () (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:4146)
TMPro.TMP_InputField:DeactivateInputField (bool) (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:4184)
TMPro.TMP_InputField:OnUpdateSelected (UnityEngine.EventSystems.BaseEventData) (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:2161)
UnityEngine.EventSystems.EventSystem:Update () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)
looks like this is from the OnEndEdit event. i'd bet you actually selected the static parameter option and left it blank in the event field. you need to select the dynamic method
https://unity.huh.how/unity-events/dynamic-values
i know how to fix this, faced a similar problem before
Hey guys, I have a problem. The slider component gets given a value however when the scene is loaded again the value of the slider gets reset back to its max. Anyone know how to fix?
Alright, so why don't you share the solution instead of saying you know how to fix it?
are you saving that value somewhere? and if so, are you loading it again when the scene is reloaded?
you have to save or store the value somewhere so you can load it . . .
Nah, let me get onto that. Ill store the value of the slider and load it when the scene loads
Cool got it
sorry for the late reply, is it this? cuz i set it up correctly (i hope)
you did exactly what i guessed you had done. please click the link
This is like the sixth time I've seen you say exactly this and then not actually give any solutions. <@&502884371011731486> can check your history. This is clearly a troll account who's wasting everyone's time
hello ive never made a game before and im trying to install xr interaction toolkit but its not installing
this is a code channel
oh im asorry
yeah they 100% have to be trolling. it's the dipshit guy
the dipshit guy?
DAMN goat user love you mwuah (no homo)
Yes. Also the one that called praetor a smartass. He is our crown jewel!
you know exactly what i'm referring to
i am just a man
!ban save 1224236792354705408 Ignoring warnings, trolling
legends_of_the_summer was banned.
since the dipshit guy is gone, can i ask if I could re-ask an earlier question that is in a thread before cuz its yet to be resolved :<
Did you change your function to the dynamic one that passes in the string as a parameter?
yuh its fixed
but not this question haha
#1230148774198775818 oh here
omg man
vs and unity does not like me
I need to connect my vs every time I start unity
it is super annoying and I now I forgot how to connect them
that typically means unity is unable to write to the registry to apply the setting. close unity and the hub, launch the hub as admin, open unity, change the setting, close both, and relaunch normally and it should stick
how do I change the setting
wdym? it's the setting you've had to change every time you've launched unity so that it would connect to vs correctly
!ide 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
How could i change the pitch of an audio source each time it loops from script? I'm having an issue with my sfx moving audio, sounding repetitive.
instead of looping, have it play every time the player steps. then you can randomize the play before playing each sound . . .
I dont mean player moving, i mean moving a object.
The audio is played and looped, depending on if the objects velocity is over 0
okay another question:
[SerializeField]
BoxCollider2D vault;
[SerializeField]
BoxCollider2D itemCol;
i have two different collider, what i wanna do is when the vault is opened, i want to remove the box collider on the vault and enable the box collider for the item inside, i wrote something like this:
private void openVault() {
vault.enabled = false;
itemCol.enabled = true;
}
I put this script in the InputField, reason being I wanted to open it when the vault password was correct, something like this:
public void CheckPassword() {
switch (password)
{
case "combine":
ChangeVaultText("Vault Unlocked!");
openVault();
break;
default:
ChangeVaultText("Wrong Password!");
break;
}
}
However when i go to interact the vault, both my boxcollider2d variable were reseted to none, when i assigned it before play mode, is separating the script necessary, or is there something im doing wrong...
nothing in this code would set the variables to None
it's probably different code you didn't share that's doing it
are you trying to assign those variables in Start or Awake or something?
Start
waut
So why are you also trying to assign them in code?
wait
public void Start() {
vault = this.GetComponent<BoxCollider2D>();
itemCol = this.GetComponent<BoxCollider2D>();
}
so i dont need to dothis?
Didn't you already assign them in the inspector?
ye i know, but when would this be viable
is it just never
Well never because both of those GetComponents would end up returning the same collider lol
while the object's velocity is greater than 0, you can randomly change the pitch based on the length of the audio . . .
In this case they return nothing because you don't even have a BoxCollider2D on your object
damn, guess i need to watch more yt tutorial and learn again :/
Did you read the error message?
I get it to a certain extent, but mainly because some tutorial tell me to type it so I just type it, I guess it means this variable's collider2d component? and =is equal no?
Then why did you post 3 scripts, none of which are the one with the error?
= is the assignment operator
it puts the thing on the right into the variable on the left
this.GetComponent<BoxCollider2D>() is a function that returns a Collider2D component attached to the same GameObject as this which is your script
Fixed thanks
so it's just going to find the first BoxCollider2D it sees on the same GameObject as your script and put it in your variable
ohhhh hahahaha i feel so stupid now
since you don't have ANY BoxCollider2D it will just return null
also if there were more than one, you wouldn't get to pick which one it finds
ah ok, so next time I should just assign it with public BoxCollider2D name << and put it in the inspector
no
[SerializeField]
BoxCollider2D vault;```
this is completely fine
no need to make it public
you assign it in the inspector
you just don't need to assign it again in code if it's already assigned in the inspector
pick one or the other
I gotchu :> thanks for the quick tutoiral my guy
How do I disable a collision detection method when there is a trigger detection method, or should I just find another way becuase I have overlapping colliders
You can disable the collider. Or put a bool in OnTrigger that does an early return when false
if (!checkTrigger) return;
Hey, so I'm having some issues to remove a hero/gameobject from a slot. the adding of hero works fine but I just don't know what might be the error since I'm getting no errors in unity.
Here's the code
using System.Collections.Generic;
using UnityEngine;
public class EquipCharactercopy : MonoBehaviour
{
public Transform[] heroSlots; // Array of transforms representing the hero slots
// Function to add a hero to a slot
public void AddHero(GameObject hero)
{
// Find an empty slot and add the hero to it
foreach (Transform slot in heroSlots)
{
if (slot.childCount == 0) // Check if the slot is empty
{
GameObject newHero = Instantiate(hero, slot.position, Quaternion.identity);
newHero.transform.parent = slot;
break;
}
}
}
// Function to remove a hero from a slot
public void RemoveHero(GameObject hero)
{
// Find the slot containing the specified hero and remove it
foreach (Transform slot in heroSlots)
{
if (slot.childCount > 0 && slot.GetChild(0).gameObject == hero) // Check if the slot contains the specified hero
{
Destroy(slot.GetChild(0).gameObject);
break;
}
}
}
}```
I placed the RemoveHero function into the button event, but it's just not doing anything
is anyone here familiar with RuleTiles?
im trying to make a game with an ingame level editor and i really want to make it possible through a script to place a ruleTile (use the ruleTile brush) on a tilemap but i dont know whether that can even be done or how
First step: Make sure the function is running. Put a log in there, log heroSlots.childCount before the loop
is anyone here familiar with RuleTiles?
im trying to make a game with an ingame level editor and i really want to make it possible through a script to place a ruleTile (use the ruleTile brush) on a tilemap but i dont know whether that can even be done or how
this is my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Tilemaps;
public class LevelEditor : MonoBehaviour
{
public int selectID = 0;
[SerializeField] Image[] tileIcons;
[SerializeField] Image selectedTile;
[SerializeField] Tile[] ruleTiles;
public Tilemap tilemap;
public void SelectTile(int selection){
selectID = selection;
selectedTile.sprite = tileIcons[selectID].sprite;
if (selectID>0)selectedTile.color = new Color (255,255,255,255);
}
private void PlaceGroundTile()
{
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cellPosition = tilemap.WorldToCell(mouseWorldPos);
tilemap.SetTile(cellPosition, ruleTiles[selectID]);
}
private void placePrefabTile(){
}
public void placeTile(){
if (selectID == 1){
PlaceGroundTile();
}
else if(selectID>0){
placePrefabTile();
}
}
}
how do i make it possible for my character to look around
Did you look around for any tutorials?
i shoud prob of done that first
how can i check if an animation has finished?
can u not just start it then see?
I mean in code lol
just use an animation event
im incredibly new
and slow
can i get assitance with making my character walk
animationstateinfo
#854851968446365696 how to post
was thinking of that but how do i detect if the event is on or off?
the event happens when the keyframe is hit.
No such thing as event on and off
I'm doing something with the animation event to instantiate the weapon and destroy it
so whats the problem ?
was jsut curious if there was another way but i will try it my way lolol
another way of what? animation event is exactly perfect fit here..
If you know that the animation will always reach the event, then it's fine.
If the animation might end earlier then you can check AnimatorStateInfo from a script like Steve suggested.
Third option is StateMachineBehaviour.OnStateExit
Does anyone have that straigth line before 1 on the keyboard and after Escape?
thats true maybe event might not hit if in transition
Yeah I know now lolol
not sure where the code question is here..
I dont have it on my keyboard and i need to make or
which keyboard style do you have?
75%
which language
I have Windows if thats what you mean?
omg
how is this not a troll post rn
what is "normal"
ENGLISH
was that so diffcult?
no..
its above enter
do you no know that each language has it's own keyboard layout?
there are many kinds of English, which one?
european keyboard..
Yes.?
what character is above the 3?
Like fn3 or the other symoble on the three?
Then i becomes an #
ok, so that is a US or international keyboard so the or is the key above the enter key with shift
Thanks!
oh hang on i think it might be on a different script
that'll be it, it was referring to my camera controller rather than the player which I shared above
is there any way to organize variables in a way so i can collapes them by clicking the little minus symbol without then being only able to access them with something.variablename
use regions . . .
regions are purely visual
For the first question - #region
For the second question - structs or classes
also
silly me
i meant without only able to access them with something.variablename
mb
so yea regions
doo you have stack traces on those ?
didn't grab it, I just looked at any possible script that had anything to do with aiming and found the problem there
Well the errors should still be there, right?
Oh, you fixed it? Nice
yeye, i'll probably delete the post as to not confuse people
{
if (MerchantPrice >= PS.Coins)
{
PS.Coins -= MerchantPrice;
PS.Merchant++;
PS.DMG++;
MerchantPrice *= PriceMult; WRONG
}
}```
yo
so i know the issue i know where it is located but i do not know how to fix it
i know the issue too
So are you going to actually say what the problem is or are we just gonna have to guess
i cant convert a Float into an int
i litterally marked it with wrong
can i get help
the line where it says WRONG that code is wrong
with animations
i need to convert a float into an int
So make it not wrong?
#854851968446365696 how to ask questions
and thatsn ot possible right?
Hey there we go that's a thing
who says?
How do you intend to handle decimals? Rounding or truncating?
well a Float is a Variable That Holds Decimal Numbers a Int holds whole numbers
so chop off the decimals
ez
thats literally all it does
i cant round the decimal i want the price of the merchant to increase by 1.2% so basically MerchantPrice Times 1.2 which is Price mult
Okay, so, what do you want to do with the remaining decimals when you try to pack it into an int? Round or truncate?
their not remaining decimals tho i need for it to be a decimal number
If you need it to be a decimal number why is it an int
coins is intiger no?
Yes
The coins is the Int and The Price Mult is a float
so how do you intent on dealing with end result of multiplying by decimal
if you get decimals as result
I don't know what coins has to do with this
so bassically everything someone buys a merchant the price of the merchant multiplies with the PriceMult
That's not on the line your error says
What if i make the Merchant price a float to? the additions in my game is mostly using whole numbers i think it should technically work
You still didn't explain how you intent to handle remainder
wdym by that Remainder
When you multiply an integer by a decimal, there could be a decimal remainder
In order to set an integer variable to a float value, you need to decide what you want to do with that remainder: Rounding or truncating (or floor or ceiling I suppose but those are kinds of rounding)
that a i do not know, as i barely know what a decimal remainder is
its basic math my guy
This is not the server to learn middle school arithmetic
you really weren't joking when you said you did not even know basic math
Oh
where im from we call it smth else
well we could just round it
Finally, an answer to the question I've asked like a million times
sorry i tought u meant to round the PriceMult which would then be roudned to 1 making the math pointless
Okay so I'm basically a full unity rookie that has just started to code a simple little remake of the game Doodle Jump and I was wondering how I would set up the camera system?
Cinemachine!
Basically what I have now is a trigger box so when the player enters the camera that's locked to that object will start to follow the players movement until the player leaves the trigger
But the issue I am facing is that the camera is moving along the X axis as well
Cinemachine indeed!
I want it to be locked in the Y-axis only
dont worry buddy, they are patient with me, they will be with you too
I just got cinemachine and haven't touched it way too much so I don't know it's capabilities
public void BuyingMerchants()
{
if (MerchantPrice >= PS.Coins)
{
PS.Coins -= MerchantPrice;
PS.Merchant++;
PS.DMG++;
MerchantPrice *= Mathf.RoundToInt(PriceMult);
}
}``` is this how i use Mathf 😭
i dont have an error
Why are you rounding your price multiplier
gimme 1 sec
just write a script that makes it so that the cameras y is based off of the players y
thats all you really need
ignore that, that was indeed a stupid move
Yeah but as of now I have a scripts that basically just adds the player's movement onto the trigger box
What would I write to lock it to Y?
So when the player enters the camera starts to move upwards along with the player
Cinemachine
Literally has a feature that does exactly this
thats the thing what do i do with it?
like MerchantPrice *= Pricemult = Mathf.RoundToInt(Answer)
deadzones and follow areas
It's in the package manager
@swift elbow bro really hating on a tool, its like hating on a Chainsaw
Why the two assignments in one line?
I have cinemachine but where in cinemachine would you find the deadzones and such
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineOverview.html
Look at the "Composing a Shot" section
idk what to do with it tho, i need to Round the Merchant price is that smth i should do in 1 line or in 2 seperate
I mean, if you have a flathead screw you're gonna have a ton of trouble using a phillips on it
i could do it without cinemachine
Yes, but why would you
you could also do it in assembly code
Cinemachine should almost just be the default camera in unity
And this opinion comes from which bias exactly ?
the correct one
I can't seem to find it?
Then you do not understand it well enough. It is objectively easier
nah jk
Is it the one named "CinemachineVirtualCamera"?
You could also code it by carving channels into a large flat rock and pouring copper into the channels to rebuild an ALU and CPU from the ground up
Oh so like the same opinions as dogs
ive justnever used cinemachine
I have a Cinemachine 2D camera
yes
That would be the camera you'd add the transposer to
Then why are you even stating an opinion on it?!?
i said its harder to me
So it's the CinemachineBrain?
look im doing
M * P then i need to round the answer which is still M how do i do that
how do i round the answer after the calculations are done
because ive never touched it
But you haven't used it, so you literally cannot say that. If you haven't used it, you do not know if it is easier
I really don't care if you want to shoot yourself in the foot repeatedly but don't suggest other people do so
Then round M * P
Welcome to my troll list .
doing something youve done many times would be way easier than doing something for the first ever time
bruh do i put the calculations in the brackets?
It's like saying "i've never used a hammer, but nailing nails in with my hand is easier"
No, it's on the camera. Check the link I sent and the documentation it links to
Mathf.RoundToInt(MerchantPrice *= PriceMult); like this?
Pretty sure no matter how many times you try to cut a board with a butter knife you're going to do better with a saw
it sitll isnt working btw
Why are you trying to assign a value inside the parameter to the function?
Do the math, then assign the value
ok
I lost two brain cells reading this
yeah but how do i take the asnwer and round it
Call Mathf.Round on the answer
and set your variable to it
yeah and the answer the MerchantPrice but its being useed in the calculations
So use it in the calculation
then set it to the result
You are aware you can just do multiplication without needing to use *= right
so what? Are you sure you've ever programmed before?
yes i programmed 3 years ago but i coppied all the code
so it didnt stick
https://paste.ofcode.org/v6e5a5CQ5V6TxshraHshC9 i have these two scripts where ive set up a basic number and text system but for some reason the number value doesnt change, i am not getting any errors
Let's have a race. Fresh project, who can get a third person orbit camera working faster, you with whatever and me with cinemachine
that ain't programming, so go and actually learn the basics and do youself a favour
Okay, woops client updated the requirements now it's an FPS! Quick buzz convert it!
yes
So, if this object is destroyed after getting picked up, how would the text ever display anything but 0 or 1?
Hm, it's a classified system, no outside code allowed! Reusing your old code could be a security risk!
yes, from 0 to 1
how
Do you know what the symbol for multiplication is
i make it add 1 not go to 1
a * b
Right, and it was 0
so when you add 1 to 0
it becomes 1
correct
And then it's destroyed
Okay well now I have it following the player
so it'll never be anything but 1
at this point not really, where im from we use a dot in the middle Calculators use X and programmers use *
so one of em
yes but in inspector it never changes from 0
So maybe you should look up basic mathematical operators in C#
The reason I made it with a trigger is to have it stop following the player after it leaves the trigger so if the player falls out of view the game ends
Is the are way to make the camera not go down?
well i know that *= is used for multiplications
No
that's not multiplication
that's multiplication and assignment
and i dont know what to do
wait nvm
I have build errors within my code but I don't know how to fix them. Unity isnt giving me a reason
It'll become 1 at the exact moment it's destroyed so you'll never see the 1 in the inspector
yeah
because the object is gone
im gonna chaneg the code rq
You probably already have a collider that detects when the player falls off of the bottom of the screen, using the CinemachineConfiner, you can make that collider a boundary. And then if you make that collider follow the bottom of the camera, it'll basically mean the camera is carrying along its floor with it as it goes up
CinemachineConfiner?
Damn I missed that thx
ok so there were 3 objects in the scene
getting rid of 2 fixed it
so ill make them appear as you progress
Sorry if you already answered this question but how did I lock the x axis movement of the camera?
Isn't the deadzone now following the player as well?
dont change the x
Yeah but the player needs to be able to move on the x axis
And the camera is set to follow the player
You could either just make the entire horizontal span a dead zone so the player is never outside of it, or you could use the confiner again
I'll try the confiner
public void BuyingMerchants()
{
if (MerchantPrice >= PS.Coins)
{
PS.Coins -= MerchantPrice;
PS.Merchant++;
PS.DMG++;
MerchantCounter.text = PS.Merchant.ToString();
MerchantPrice *= PriceMult;
}
}
i need help
still
Did you look up how to do multiplication
ive been trying with like 3 other tutorials which they do not work
i cant find any, if i sea1rch
how to do basic multiplications in unity C# i get Vector3 Tutoriakls
Show your search query and results
This is not a difficult thing to find
why are you searching on youtube
i learn easier with videos
obviously not
Well, since I am not a video, I'm afraid this is where my ability to help you comes to an end
tragic
have fun looking for a ten minute video with midrolls to tell you what the multiplication symbol is
doing multiplications in c# has nothing to do with unity
it basic operator in c#
yeah those only show me Int + int Float + float sometimes Int Times Int
but i need int times float
Int * float
what
so do that
it's math
seriously
like, elementary school math
i cant it tells me i cant convert an float into an int
Show what you actually did
Are you trying to store the result in an int
because as we have just explained you cannot do that
yes
no you didnt u just said to round it
So here we fucking are again
Why do you think that would work?
Rounding to an int WOULD work
do you want to round or truncate it
they said round or trucate about a dozen times..
What do you intend to do with the decimal after the multiplication
round it but HOW
yes by using Mathf.Round but what do i do with it?
And they actually answered me once and I sent them the link and now we're back in the fucking building again
you do the math
then round it
then store it in the int
Put the thing you want to round in it?
Mathf.Round returns a float thats been rounded
look i want to round merchantprice the int
And you have been told exactly how many times
Literally given the code needed
when?
yes but we are not videos
mathf.round yeah but what do i do with it
and he's already said he won't read any words
you give it the value you want it to round and it returns the value, but rounded
generally you consult the documentation like a normal person and see how its used
https://docs.unity3d.com/ScriptReference/Mathf.RoundToInt.html
literally plastered with examples..
You REALLY should have googled this yourself
https://docs.unity3d.com/ScriptReference/Mathf.RoundToInt.html
Oh, too slow
Sorry, "Documentation"? Do you have that in the form of a 10:01 Youtube Video with stock premiere pro intro and outros blasting shitty phonk music over the guys profile pic
yeah and it says this
// Prints 10
Debug.Log(Mathf.RoundToInt(10.0f));
// Prints 10
Debug.Log(Mathf.RoundToInt(10.2f));
// Prints 11
Debug.Log(Mathf.RoundToInt(10.7f));
Cool
so you know how to use it and what it returns
Yes. Do you know how to assign a variable?
lol too true
i put the thing that wants to be rounded Debug.Log(Mathf.RoundToInt(HERE));
yes
Time to make an app "Documentation to MP4"
Okay, so, assign your variable to the rounded float
Then do that. Remove the Debug.Log part, and assign it
=
you know how to assign a variable, and you know how to round a value to int
so what's the fucking problem
that's literally the only two parts of this line
ya mate , its only gonna get harder from here . Spoiler alert
so i make another variable which is going to be rounded
Sure, if you want to. Or just put the math in the parenthesis
I guess this is why microsoft has a Console app as first project being a calculator lmao
i read alot of math
Perfect. You got it then.
It is saying it does not want a decimal assigned to the int.
If you understand math, you should know exactly how to handle that with the example code above
Have you learned how to multiply two numbers together?
yeah i get it if im doing 2 * 1.2 thats 2.4 which is a float which cant be stored in a int
Awesome 
And you also know how to round a decimal number to an int now, right?
im still a lil stuck
what do you have so far
Ok, so you have a variable that takes an int
You have a float you want to assign to that variable
You have a method that rounds a float to an int
Which part are you struggling with?
yes and i know how to round it
idk how to get the answer
wait leme explain it a lil more
Mathf.RoundToInt(10.0f) like thats what i use right cool math, i need to somehow tell my code to put the answer Mathf.RoundToInt(HERERE!!!)
You just did though
10.0f
I don't get it
not really its roudning it to nothing
remember how it was suggested to you multiple times to go learn the basics of c#? you should probably do that so that you'd understand how to use variables and pass them as arguments to methods
Incorrect, you just have to assign the result
ok!
Variable = Mathf.RoundToInt(floatIWantToRound)
ok ok
This was given to you before
leme try smth
Are you trying to pass the asnwer to the function?
That's not how, like, logic works
i dont think that happened i keept asking what do i do with Mathf.RoundToInt(10.0f) and nothing was given
I personally told you = twice
well im putting the answer in the brackets
And when we asked if you knew how to assign a variable, you said yes
And saw others say it too
If you lie (even unknowingly) about knowing something, we won't know to explain it more
{
yield return new WaitForSeconds(delay);
while (true)
{
if (EnemyHealth.count == 0)
{
_enemiesLeft = true;
StartCoroutine(DelayRoundIncrease(roundDelay));
yield break;
}
}
}```
Anyone know why this coroutine is making my Unity freeze and crash.
It is called once:
'``` if(_toSpawn >= state)
{
StartCoroutine(EnemyCheck(4));
yield break;
}```
this tells you all you need to know
You don't yield in the while loop
Only in the if
If EnemyHealth.count is not 0, there's no yield, so it will loop forever
oh yeah you are right
ty
yeah
Sorry Steve you aren't a video either so they don't know how to absorb any information from you
ive been stuck on the same thing for like 2 hours
Oh, ok, I'll just block them then because they are extremely irritating
i know what i have to and i kinda know how
maybe you need a better hobby lol
i have to round the answer using (Mathf.RoundToInt(10.0f) but where do i put the (Mathf.RoundToInt(10.0f)
the reutrn value is the result of the operation
yeah but the thing is the only float i have is the PriceMult
why would you round the priceMulti..
Exactly
i cant round that float and its the only float i have
You are supposed to round the result
Round the result of the math
Like we've said
a lot
do the math
the thing is HOW do i tell the code to round the answer
mate if you are multiplying by a decimal, you will get a decimal most likley
Variable = Mathf.RoundToInt(number1 * number2)
By putting the math in the fucking function
Pass the result
to the function
that's the float you want to round
this has to be a troll post
idk how to feel about you guys saying im a troll even tho im not
How many different ways do we have to literally give you the exact answer before you just fucking do it
This is a bit below basics. If you don't know how to do this, I strongly suggest you go do a beginners course.
Do NOT use youtube. Use something like this
https://www.w3schools.com/cs/index.php
because you've been told multiple times how to do it and even got spoon fed answer and you're like "idk how i should use it"
i got some good news
let's see if this works
float = int * float
int = RoundToInt(float)
thank you for specificly letting me know what to do with the Roundtoint
im sorry for being slow
You had already been told specifically what to do with it many times
"Do the math in the parentheses" is just word form of what I wrote
"Assign it to a variable" is too
the main problem is you don't understand the basic of C# because you would know that a function returns a result
if you don't care about a result, then its void
you mean like void like method? or like nothing
void returns nothing, in a method yes.
this one returns int, meaning you can assign the result to a variable
alr well i will go to sleep, BUT before i do
public int MerchantPrice = 20;
public TMP_Text MerchantCounter;
public TMP_Text MerchantPriceCounter;
float PriceMult = 1.2f;
public void BuyingMerchants()
{
if (MerchantPrice >= PS.Coins)
{
PS.Coins -= MerchantPrice;
PS.Merchant++;
PS.DMG++;
MerchantCounter.text = PS.Merchant.ToString();
MerchantPrice = Mathf.RoundToInt(MerchantPrice * PriceMult);
}
}
``` is there an issue with this code?
i keep testing it but the Text That is the MerchantCounter isnt going up
the only way it would not go up is if yu have console error or something
Or something else is overwriting it after this runs
i dont have an error
ahh true that
but its just not doing what im telling it to do
maybe something is changing Merchant in update or something
Is BuyingMerchants even being called?
it should take 20 coins away and put 1 merchant and multiply the Price by 20%
Use Debug.Logs
Try logging MerchantCounter.text after setting it and see what it prints. This will show what that value is at that exact moment even if something is changing it later
lets see if the button being pressed is even being registered
i can see the value of Merchants as i have it as a public INT
That doesn't show you the exact value as of the time that code is running. That shows you whatever it is when you look at it
log it
oh
alr this might sound stupid but how do i tell unity to send me smth in Unitys logs??? i only rememeber using Console.WriteLine(); when i was using console
just Debug.log()?
i want to have multiple cinemachine cameras that i can switch to, but once my player respawns (i delete and instantiate a new clone of the player) the dupe only gets followed on my main camera which is then disabled, and the other cameras do not follow the new duplicate, does anyone know why this is happened
Remember when you were told to go and do the basic tutorials linked in the pins?
Well, that.
Debug.Log(Mathf.RoundToInt(10.0f)); i see debug log its Debug.Log then
why are you destroying it anyway, just reset it
Presumably, all of your other camera's are set to follow the original object that no longer exists. If you're spawning in a new copy, you'll need to go through all of them and update their follow target
I've tried doing that before, but it just wont grab the new one
How did you do that
Show
soo much less complexity if you just reset the player instead of dealing with new clones
in the long run at least
so i should just rewrite my GameManager / respawn to instead, reset instead of delete?
didnt rlly think of it in that way
Probably
imo much easier to keep track
alr i thin i fond the issue
and probably more performant than constant instantiate and destroy
its the if statement
cool cool cool, i'll try that, i needed to rewrite it anyway because im making a metroidvania and need to be able to keep track of it
thank you @polar acorn and @rich adder
Ah, it should be <= right?
bruh someone told me to do >= cause mine was wrong
yes it should have
someone said im doing it wrong tho
Do you want to check if the price is LESS than coins, or MORE than?
/> is more than
< is less than
i know but idk he knew how to programm whilsts i barely know crap
lets go its working
Then this
https://learn.unity.com/
what if i just watch brackeys C# tutorial and Unity Tutorial
Super bad idea
how
thats like the only reason why i programmed 90% of my code alone
he explained it super well and it stuck
-
brackeys specifically is really not good for beginners. They do good stuff for more advanced things, but they are not good with beginners
-
you need to know how to read docs and tutorials, so don't do videos
worst c# tuts imo
And think of the struggle you just went through
All of that was stuff that should have been easy if he taught his course well AT ALL
and it wasn't very good
isnt he loved thruout the programming communituy
popular != good (well not always)
Not in my experience. He is near-universally panned as bad for beginners
He is thought as very charismatic and decent intermediate and advanced courses
its good for picking up a feature or something to learn quickly but you should at least have fundamentals before doing so
That certainly explains a lot
i got bad news
theres an issue with the math
the original price of a merchant is 20 coins but once bought it increases to 200 coins
meaning that instead of it being 24 coins as it should since its 1.2 its 220
Brackeys is a great presenter, and he is great at giving the broad strokes of systems. His code, specifically, is sloppy and usually just exists to demonstrate the topic at hand without regard towards expandability or useability and often breaks as soon as you try to do anything else
That is a lot more than 120% increase
that is a 220% increase
So log the numbers and see which ones aren't what you expect them to be
20 * 2.2 = 44
1000%
What numbers are you actually plugging in?
Did you log them
wdym by logging them isnt that the console? like Debug.Log?
oh
My only thought is that you are putting 1.2f in the code, but changed it in the inspector
Inspector has priority
It means the same thing it meant the last time I said to do this
prob leme try to re buy the merchant as i have deleted the Float
nope
kk
uhjm
wait thats quite interesting
i buy one for 20 coins then in creses to 220
then it deacreases to 29
wait but the price isnt changing tho? its a visual bug
the numbers are off, the price in the inspector is 50 whilsts its telling me that the price is 42 ingame
MerchantPriceCounter.text = MerchantPrice.ToString("Price " + MerchantPrice);
this line is giving me trouble
When does this run
but why is it incorrectly displaying the number
When that line runs, it will set the text to whatever MerchantPrice is at the time
i think i found the issue lol
the code is only activated oen the merchant is being bough
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class Shop : MonoBehaviour
{
public PlayerStats PS;
public int NursePrice = 50;
public int ZoologistPrice = 50;
public int MerchantPrice = 20;
public TMP_Text NurseCounter;
public TMP_Text NursePriceCounter;
public TMP_Text ZoologistCounter;
public TMP_Text ZoologistPriceCounter;
public TMP_Text MerchantCounter;
public TMP_Text MerchantPriceCounter;
public void BuyingMerchants()
{
if (MerchantPrice <= PS.Coins)
{
PS.Coins -= MerchantPrice;
PS.Merchant++;
PS.DMG++;
MerchantCounter.text = PS.Merchant.ToString("You Have " + PS.Merchant);
MerchantPriceCounter.text = MerchantPrice.ToString("Price " + MerchantPrice);
MerchantPrice = Mathf.RoundToInt(MerchantPrice * 1.2f);
}
}
public void BuyingNurses()
{
}
public void BuyingZoologist()
{
}
}
this is my whole code
ignore the nurses asnd zoologist
Change all those prices to private. Just curious if something else is changing them
its not a math bug the math is correct its displaying the wrong numbrr
Code runs top to bottom, one line at a time. You set the text, then increase the price
OMG I KNEW SOME CODE EWNT TOP TO BOTTOM , i tought i was java or lua i forgot everycode does that
If by "some code" you mean all code in every programming language on the planet then yes
I don't know of any code that doesn't
"i tought i was java or lua i forgot everycode does that"
yes that is indeeed what i meant
didnt fix it btw
what did you actually change
{
MerchantCounter.text = PS.Merchant.ToString("You Have " + PS.Merchant);
MerchantPriceCounter.text = MerchantPrice.ToString("Price " + MerchantPrice);
PS.Coins -= MerchantPrice;
PS.Merchant++;
PS.DMG++;
MerchantPrice = Mathf.RoundToInt(MerchantPrice * 1.2f);
}```
put the counters to the top
This is the same thing
You're still changing the text before you change the value
top to bottom
should i put the variables below then?
Put the code in the order you want it to run
i want it to be put in a way that makes the code work
So what order would that be
Only you know what you want the code to do
only god knows 🙏
leme try to put the variables below the if statement
but wait
Then you've reached the end of your journey
I would put the numbers to private. If the text is changing that much then something might be changing them
And you would likely want the text to update LAST inside the if statement
You put it first, which is the opposite of what digi was suggesting before
once the game starts the prices wont be set til i buy a merchant which is not possible as the prices arent set yet or it would be as i manually set them to 20
sorry not the sharpest knife
you know that
wait it seemed the change smth
i wouldnt get o see 24 before
now i go to 500 before the price changes
that did smth
Just, think about it. If you write down a price on a piece of paper, and then you change the price, would the paper magically change to the new price?
no
So, in your code, if you change the text and then change the price, would the text magically change to the new price?
ok i get it im sorry i already put the code last
i fixed my mistake alr
@summer stump u said to put all numbers to private right?
anything that you dont need public should be private, and if you need it in the Inspector you can use [SerializeField] on the variable
Should i put the TMP_Text into [SerializeField] too
if you dont need it public and you need it to show in the Inspector
i do need to TMP text into inspector
kk
anways
do you have any clue on why my Text is displaying the wrong information sometimes?
because your giving it wrong information?
it only displays what you tell it to
no thats the thing
prob ur not updating the text after changing values
it only shows the wwonr number sometimes
yeah but then why would i spike from 49 to 500?
It only ever shows what you tell it to. Ever
things don't just happen by themseleves, debug and find out
So something is changing the numbers, you are updating the text in the wrong place, or something else is going wrong in the logic of the code
thats the thing idk whats changing the value
That's why we have all suggested debugging it
these are the only refrences to MerchantPrice
ive only used This Variable in this script too
@rich adder i rewrote the script, works beautifully, thank you and the other guy ❤️
Do you have multiples of this script?
they mean on another gameobject in the scene
Debug.Log($"MerchantPrice: {MerchantPrice}");
Put that at the beginning and end of th BuyingMerchants method
wait i found smth interesting
that not supposed to be here
i mean its not changing the code as i am never clicking on the Zoologist
I don't understand what you mean about the Zoologist
look i have three charachters
nurse zoologist and merchant i am working on the merchants and this was on the zoologists
is this like your first project ?
technicaly 2nd
what happen to doing like tetris or angry bird, this sounds complex
its a clicker game O-O
Seems like an idle game to me
that's probably fine
just requires math
bro its so easy that i wrote 90% of my code and it worked with no issue
no the price doesnt change
its a visual glich
Where do you set the text before this function runs
wdym by set?
What is the text set to before this code ever runs
the text is in the same Script as everything
You are wrong. It is NOT a visual glitch
[SerializeField] int MerchantPrice = 20;
20
no, the text
the price is 20 as thats the defualt price
make the variable a property and use only Invoke event inside the set to update UI 
It took us an hour to explain multiplication I am not going to be explaining properties and events
haha yeah this would be too much of a challenge
Okay, and is that consistent with what you're seeing when you start the game
ok
before clicking anything
yes
So, if this is the only place you're changing the text, and the text becomes incorrect after clicking on it, then the price you're setting this to is incorrect
thats the wierd ting
it goes on for like 3 clicks as normal
Did you add the debug.log I wrote for you in the two places I told you to put it?
If so, show the console when the game runs
then boom 500
i did
the price increased normaly
So, show the logs
gimme 20 seconds i deleted them 😭
What's wrong with that? (NullReferenceException)
1 script:
public void DropItem()
{
foreach (Transform child in transform)
{
child.GetComponent<Spawn>().SpawnDroppedItem();
GameObject.Destroy(child.gameObject);
}
}
2 script:
public class Spawn : MonoBehaviour
{
public GameObject Item;
private Transform Player;
private void Start()
{
Player = GameObject.FindGameObjectWithTag("Player").transform;
}
public void SpawnDroppedItem()
{
Vector2 PlayerPos = new Vector2(Player.position.x + 2, Player.position.y - 1);
Instantiate(Item, PlayerPos, Quaternion.identity);
}
}
what line
!code 👇 and share the full error, especially the stack trace
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
child.GetComponent<Spawn>().SpawnDroppedItem();
And does that match what you see on the text box
Then either child is null or it has no Spawn component on it
but once i click on it with 50 coins it goes away
Now click it one more time and show this screenshot again
then ti increases to 660 and then 72
Show it
which is wierd
because you were taking a long time to post a screenshot
Whenever it's showing the wrong number, show a screenshot of the inspector for this text component
Wait a minute I just realized something
so when i got 500 coins then i had to actually pay 50 coins when i had to pay 60 coins i had the bug with 600 coins
now i need to pay 103 and it shows as 11033
my code 🙂
why are you using the number inside of its own format string
Dang, I saw that earlier and then got distracted! Dropped the ball
Thought process: "huh, that looks wei- oh I have to do this other thing"
tbh i enjoy that yall are not screaming at me anymore
well this is a more interesting problem than "how do multiply"
I don't remember that happening honestly. Just being a little short
haha yeah since its string the ide doesn't throw an error lol
wait so what do i do now?
It's just that occasionally, the number happens to be a valid numeric format so it applies that
if i remove the 2nd Merchantprice it removes the counter
but if i delete PRICE and Merchantprice theres only THE counter
The parameter of ToString is a number formatter
You don't want to put anything in there
so i dont put stuff in her if its a number formatter?

