#π»βcode-beginner
1 messages Β· Page 436 of 1
What do you see if you run
dotnet --list-sdks
In a console?
i would love to but im not sure how to do it with a list
a list of her SDKs in programs and features from the other night #π»βcode-beginner message
thats what i get... which looks like an issue cause theyre all x86
also when i look in my apps through windows i see sdks that are x64
I'm not sure if these are installed or just installation files..?
Where are you seeing them?
im seeing them in my apps and features when i search up .NET
https://gdl.space/ekipahabob.cpp i am having a problem with this is that it's supposed to show how many muons with tag names "Muon1" "Muon2" and "Muon3" from different scenes there are while i am in the world select screen but it is not showing how many muons theere, how can i fix that since when i put some muons in there, it shows how many muons there are, but i want it to show how many muons there are in every scene?
So if I have a list of Transforms , how do I transform the RotateTowardsTarget method work with the list since rn the method works only for an enemy but I want it to rotate towards the first enemy that enters the radius
Or wait
I don't even think I need to do a list
Since I just want the turret to turn towards the first enemy that enters the radius and shoot at the enemy then when that enemy dies , the turret shoots the next enemy
Idk if that's a good way too do it icl
don't anyone understand what i mean?
Access the first enemy in the list and assign that to a target variable. When that enemy is dead, rinse and repeat . . .
it's one of the beings that you need to rescue, like collecting them
those are muons
when you need help you probably shouldnt use names that only exist in your game like that
makes it hard to follow
so you have some items in different scenes and you wanna display how many there are in total?
So basically do an for loop?
those items, yeah
if the state doesnt change you could do something like using a scriptableobject assigned to each level and store how many of your objects will be in the scene
now if you play the level and the amount remaining changes and you wanna reflect that in the other scene youll need to figure out some sort way of saving data because scriptable objects arent for saving changes
the counting how many muons there are in each scene only appears in the world select scene, also how do i do that?
something like
public class SceneData : ScriptableObject
{
[field: SerializeField] public int MuonCount;
}
oh you should probably add [CreateAssetMenu(fileName = "SceneData", menuName = "ScriptableObjects/SceneData")] in there above the class definition
i mean i guess a simpler solution if the count is static is to just make a static class that holds that info and you can write it in code
should i put the script on somewhere?
i think this might be better if the count isnt changing throughout the game
You're just accessing the first element of the list, so there wouldn't be a loop . . .
but to answer the question you could create a monobehaviour in the world select that references the SceneData class. if you go the scriptable object route you can add more data to it about that level like scene name or whatever
I figure you have a trigger that adds enemies to a list when they come into contact with it. That gives you the order they entered . . .
public static class MuonManager?
tried that and yet the how many muons there are in every scene still doesn't change the number
Hey guys, do I need to use getter and setters for all my variables inside player etc? or just the most important ones? If you are creating a game alone should I even care about this?
You don't have to, no. You only care if you care, it's not necessary.
Only for those that need to be accessed from outside the class.
If you want to make good habits, you should probably make use of good practices, even if it doesn't matter a lot in the current circumstances.
But that could make the code 10x bigger, and if u are coding alone and know what u are doing why create so many more lines just to make sure nobody else will change ur variable in a scenario I am alone in this?
They can be single lines
It shouldn't. First of all you can use auto properties, so it's just replacing the original field. And second, you shouldn't have that many properties in the first place.
Ok, understood, thank you
if ur coding alone u get to do wetf u wanna do π
The "make sure nobody else will change ur variables" is in 99% of cases a safeguard against your own mistakes and bad code.
the person that will fk u over the most is ur past self
hahaha, got it. Makes sense.
I will try to start using it in a new small project game I have.
you can use auto implemented properties
its 1 line
yea, thats what Osteel mentioned
I will do a research on that. Thank you
Even when not using autoprops, it would be 2x bigger for ONLY the properties (one line for the propery and one for the backing field).
Meaning less than 2x.
I'm really really struggling with tracking down the cause of NullReferenceException.
is there an in editor way to see what is wrong with the script? Everything was working until I started moving the Start() functionality into a Setup() function called in order in a game manager script
now its just constantly tracking down NullReferenceExceptions
it tells what line of the code threw the error
find that line.. see what references u have.. and debug them to check if they're assigned
for this current iteration of the error, its caused a script passing itself into the state machine currentState.UpdateState(this);
theres no written backing field for auto properties
this worked perfectly before until I refactored the code to be setup in a manager script
well i wouldnt see how this would be null.. soo maybe its currentState thats null
Yes. That is why I said when not using autoprops
whats the big deal with an extra line per property
It is not a big deal, that was my entire point.....
i mean i guess it doesnt matter its your choice
I was pointing out that there is no possible way it would be 10x
Even without knowing about auto properties, it would be less than 2x max..
It seems you misread what I was said and took it to mean that it is a bad thing? I meant the exact opposite
No worries. It happens. That makes things more clear, cause I was confused haha
adding a null check makes the editor itself crash. I'm at a complete loss
tf?
well, it hangs forever, not crash
yes..
its slowly going to become the standard
if ur learning just use the Input. class for a while..
then u can learn the input system later
you can even have both in ur project..
If you plan on allowing mutli-input (like keyboards and controller and touch) then it simplifies things A LOT. If you are only using keyboard, it is still worth it, bit the Input class can still be preferable for its ease
is there any way to center the players mouse on the screen?
yes its Cursor.lockState = CursorLockMode.Locked;
i know how to use input
nice that i can use both
i have been learning unity for about a year now is that still beginner status
ok cool cause i feel like a beginner
im 3.5 years.. and i still am
yo why is this spawning 2 balls when i move the ball out of the trigger zone void OnTriggerExit(Collider other) { if (other.tag == "ball") { //ballCount--; //Debug.Log("Objects in trigger: " + ballCount); StartCoroutine(outzone(other)); } } IEnumerator outzone(Collider objToDestroy) { Destroy(objToDestroy.gameObject); yield return new WaitForSeconds(1); Instantiate(ball, ballSpawner1.position, ballSpawner1.rotation); } }
put a debug in ur coroutine.. but im sure that'd run twice right?
oh yea let me try that lol
ok yea its getting send thru twice.
im gonna try and disable the collider rq
I ended up have to assign all GetComponent<>() references in one script instead of the Start() in every other script attached to the GameObject and the bug went away. I wish I knew why this worked lol
ohh was it trying to reference an object that wasn't set up yet?
that stuff can happen w/ singletons and stuff that set up in Awake().. if another script tries to grab it in its Awake().. there could be a race condition
Awake() set up self Start () set up others
It was an instantiated GameObject from a prefab that had all the scripts attached so I still dont understand
ohh yea, if all it's dependencies were on the prefab itself i wouldnt understand either
but im glad u got it working
!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 am trying to do a load and save system
i get an error saying "object reference not sent to an instance of an object" on line 48 and 61
so it must have to do with foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects
i dont think that the IDataPersistence script should have this issue since its an interface and not a monobehaviour
the IDataPersistence script is this
`public interface IDataPersistence
{
void LoadData(GameData data);
void SaveData(ref GameData data);
}`
public void Start()
{
LoadGame();
this.dataPersistenceObjects = FindAllDataPersistenceObjects();
}``` flip these around
that works lol ty
why does that work
your very welcome..
dataPersistenceObjects is not initialized before it is accessed in the LoadGame and SaveGame methods
just think about the flow u have
it helps me to scratch out whats happening on a piece of paper when working on systems like a save system
what sucks is that i am too clueless on the topic to not use a tutorial so then i get stumped when roadblocks like that come up
i also use tons of comments
thats what this channel/ the forums/ and other like it are for..
specifics..
for me.. in my opinion.. i'll watch a tutorial.. i'll do the exact same thing..
then i go back and re-read it.. and write out comments to try to figure it out on my own..
then i try to implement it again but on my own this time.. and thats when i'll go to google and read-up and learn about certain things
that i used for the tutorial that i didn't actually know about (or how it worked)
then eventually.. you'll be able to code the same thing w/o any help.. besides googling functions and keywords
that seems like a good method ill save that
the comment part really helps
when i learn how it works i will comment
they dont always have to be perfect π
im continiously having this issue where my c# dev kit is targeting the wrong format .net sdk. instead of x64 its targeting x86 and i cant do anyting and I was wondering if anyone knows how to change what sdk is targeted
im using a 64x i believe but possible an 86x is there a way to check?
System Information -> System Type
x64-based PC
have u googled how to retarget sdk
some x86 some x64
well they put both i think
yes and i found a solution in vs studio code but it doesnt apply the same way
is it ur VSCode thats busted?
and i think i jut found something that says i can do it in global.json but idk where that is
since ive had the issue ive tried reinstalling 3 times
thats the exact error message
should i delete it again and do the walkthrough again
maybe ur just missing a step
idk im just reading around.. my .NET install was simple
i saw that thread but ig i glossed over hat
i just went online and found the .NET 8 / 9 on their website and installed it
thats what i did as well
id uninstall and reinstall the SDK
ill try that if uninstalling the extension through vs code doesnt work
yeah that didnt work
@steep walrus tbh someone shoulda helped u fix this by now..
i just don't have the expertise to help.. other than just googling along-side u
nah youre all good its a complicated problem it seems i also am just trying to lean and its really unmotivating that i literally cant even start
i feel like also everything i google is like slightly different than my situation and there is a chance ive missed the solution cause im pretty confused
Why when instantiating from a prefab can no scripts attached to the prefab access each other using GetComponent<>()?
why the controls (text) are reblind but the player still moving with old movemeny?
he still moving with adw
same.. most things i find aren't Unity related.. and they say u can change it in global.json which doesn't exist in any of My projects..
when i zero in on unity stuff it just says, make sure to install the correct sdk, restart it, and in unity make sure u have the correct plug-in installed and updated
Hey guys. How are you?
Can you help me with particles? I hung a script on an object that should protect from particles, but there just ignore me and collision. I'm used mesh collider for home
the movement won`t change either
#β¨βvfx-and-particles probably better of place.. but what happens if u change the Collision -> Type:
help please
It doesn't work - the first
is the second - I want to make it rain, so it won't work, but thanks for helping π
Can we make 3d object move in 2d tilemap?
Affirmative
Can you screen your settings for particles?
https://assetstore.unity.com/packages/vfx/particles/cartoon-fx-remaster-free-109565 i believe it came from this asset pack (the rain particle)
also gotta have good colliders on the objects (convex or primitive)
ahahaha, I have now created new particles and they are working))
maybe problem with my current rain
what do you guys prefer for input systems? My personal preference is something like the new input system but i like events and binding them in code rather than the editor, I also rather not lookup action names using strings if i could help it. any recommendations?
getting a nice input setup has always been one of the roadbumps whenever i start a new project
Thanks for helping π
an InputController with C# events is a simple setup to start with. you could create SOs for the action names. technically, you're still using strings, but they're SO assets named after each action. if one is misspelled, the SO (name) is the only point of failure to worry about . . .
!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
what this mean
sorry but by InputController you'd be referring to a custom script right? I am not against doing that, I'm just not sure if you're referring to a custom script or something already implemented in Unity
I have a problem with the unity editor UI where's the best place to get help?
I keep getting blank UI panels like this everywhere and need to reload them, or sometimes i can't expand the transform component. I've tried resetting the layout, didn't work
I'm sorry if I'm posting in the wrong place
unity version is up to date
How do I add +10 to the 'right' property? ```cs
loadingPanel.right += 10;
CS0019 Operator '+=' cannot be applied to operands of type 'Vector3' and 'int'
so i cant add integers onto vector properties
i was thinking of converting the vector property to an integer and then adding it back but i dont think it would work
What type is a loading panel?
its a UI panel
So it isn't a Rect Transform?
When I click the "werk" button, I want the panel to slowly go up and then when complete add +1 money
Show where you've declared it
'right' is part of rect transform
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;
public class buttonScript : MonoBehaviour
{
public RectTransform loadingPanel;
public void Button()
{
loadingPanel.right += 10;
}
}
So it's a Rect Transform
yeah
The right property likely isn't what you're seeing in the inspector but the specific axis relative to world space
this is what im trying to acheive with a script
https://gyazo.com/3df194478518d02a23afbcc9f47d6be0
You should instead modify the Rect by assigning it a new Rect with your wanted values
https://docs.unity3d.com/ScriptReference/RectTransform-rect.html
so i should add my required amount onto the "right" and then assign that as a new rect?
and repeat that 100 times until its at my desired value?
Not sure why you'd do anything 100 times but if you're wanting to modify the properties of the rectangle (left, top, right, bottom, z) your wanted property would be the rect member.
im making an animation. thats what the gif i sent depicts. if im changing the rect, i need to change it by small increments to make it appear as smooth. this will make it look like it is "loading". I will stop applying the increments once the value is greater than or equal to right===0
so i will need to change the rect mutliple times
which i dont think is the most resource-efficient way
Whatever the case is, the right property is referring to your object's directional axis-right and not the right dimension of the rectangle. You'll need to modify the rect property if your intentions are to modify that "right" field shown in the Rect Transform component.
the documentation you sent has the right properties listed for a UI label. ```cs
void OnGUI()
{
//The Label shows the current Rect settings on the screen
GUI.Label(new Rect(20, 20, 150, 80), "Rect : " + rectTransform.rect);
}
How would I do this for a panel
also where in this script do i define the panel that i am trying to change the property of?
You might want to use the offsetMin and offsetMax properties of RectTransform
how do i do that?
i dont have a lot of experience with c# but i do with other languages
Or an animation would be good too, probably
Look it up in the docs
animation is what im trying to achieve except im doing it through altering a property to create the effect
idk if u can do it another way
offsetMax is the upper right corner of the rect
offsetMax.x would be right
Play around with the values to see how it works
i wanna instantiate an array of prefabs inside a circle but i dont really understand random.insideunitycircle, i didnt quite understand the documentation, help any1?
Which part don't you understand
It just returns a random point on or inside a circle of radius 1
As if the circle center is at (0, 0)
If you want to change the radius and center position, then simply do:
Vector2 randPos = Random.insideUnitCircle * spawnerRange + spawnerPos;
nvm i understand it now, all i need to do is to add it to a Vector3 and then add the vector3 to the position i want it to start and to multiply by the range
It says I'm using only float values that apparently... Can't be smaller than 1. or like can't have dots.
using System.Collections.Generic;
using UnityEngine;
public class Walking : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A))
transform.position = new Vector3(transform.position.x - 1, transform.position.y, transform.position.z);
}
}```
How do I write with stuff smaller than 1
What says that?
0.1 is a double. 0.1f is a float
π 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.
Anyone wanna help me refactor this monster? https://gdl.space/zalugonaqi.cs
I have 4 classes that extend Item, which are all created slightly differently.
My code is a huge mess right now and I find it very hard to restructure stuff like this.
On the plus side, it does work, so I don't hate leaving it like this, but I kinda do a little π
doesn't look all that huge to me, but I'd start by using the built in refactor method of Extract Method
jez tons of if statements. @topaz mortar have you ever heard of never nesting? For most people it really helps to keep your if statements more readable and clear
You might want to look into it, it's quite nice
pls help in #archived-code-general , dont wanna repost it here
here my character is a dynamic rb2D and the platform is static rb2D. When the platform is moving down, the player seem to be not "stand" on it, instead it keeps teleporting, how can i fix this or what is the keyword for this problem ?
yep, your own script, whether it's InputController, InputManager, or by any other name . . .
i actually just finished making it :D
yeah this seems pretty good so far
(surely i shant run into any issues later on from poor design choices)
what is the reason that there is no checkbox for the twitch script?
No unity messages (methods)
Unity trying to be smart and failing π
it doesn't have a Start, OnEnable, OnDisable, or an Update method (unity message) . . .
aight thanks guys
You won't need that disable/enable checkbox if there isn't anything to disable/enable (callbacks that Unity would run)
Unless, you know, you're using the enabled property for something in other events π€·ββοΈ
It's rare, but when it happens it's frustrating they tried to be smart about it instead of just giving you the checkbox always
@fossil zephyr Assign the rect property a new rect of your liking or as suggested, modify the offsets - space is relative to anchors.cs var rect = whatever.rect; //modify the rect whatever.rect = rect;
do i put panel as "whatever"?
#archived-code-general message Help π
Hello guys im new and trying to learn some unity basics any tutorial for a total beginner ?
public static event Action<Equippable, int> UnEquipEquippable;```
Can you not overload events?
#πβcode-of-conduct dont crosspost, saying that you dont wanna repost doesnt mean anything if you still do it anyways
Also you likely arent getting help because it is very vague and more of a beginner issue in the general channel. Try to narrow down the issue rather than just saying it doesnt work. You should have a general idea of what line of code isnt working. Add debugs to see whats specifically not working
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
no, it doesnt really make sense for this. it would be like if you add an int and float with the same name.
You can also check the link from SteveSmith or the resources in the pinned message from vertx
that's not even overloading: you're declaring two different types with the same name . . .
Hey I'm moving to unity, And I'm making a system to walk and jump around.
And it just skips through some steps to do things.
Full script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walking : MonoBehaviour
{
// Start is called before the first frame update
float JumpHeight = 0f;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A))
transform.position = new Vector3(transform.position.x - 0.005f, transform.position.y, transform.position.z);
if (Input.GetKey(KeyCode.D))
transform.position = new Vector3(transform.position.x + 0.005f, transform.position.y, transform.position.z);
if (Input.GetKey(KeyCode.W))
transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z + 0.005f);
if (Input.GetKey(KeyCode.S))
transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z - 0.005f);
if (Input.GetKey(KeyCode.Space))
Debug.Log("Pressed space... probably");
if (JumpHeight <= 0.8f)
JumpHeight += 0.01f;
transform.position = new Vector3(transform.position.x, transform.position.y + 0.01f, transform.position.z);
}
}```
What I'm focusing on:
``` if (Input.GetKey(KeyCode.Space))
Debug.Log("Pressed space... probably");
if (JumpHeight <= 0.8f)
JumpHeight += 0.01f;
transform.position = new Vector3(transform.position.x, transform.position.y + 0.01f, transform.position.z);```
What it skips to:
``` if (JumpHeight <= 0.8f)
JumpHeight += 0.01f;
transform.position = new Vector3(transform.position.x, transform.position.y + 0.01f, transform.position.z);```
It doesn't show text until I press space, but does jump for some reason.
you need brackets, without the brackets its just doing the next line only within the if statement. C# doesnt care about how its indented
oohh okaii ill check them out thanks! :)
Oh alr where do I place them?
if (Input.GetKey(KeyCode.Space))
Debug.Log("Pressed space... probably");
if (JumpHeight <= 0.8f)
JumpHeight += 0.01f;
transform.position = new Vector3(transform.position.x, transform.position.y + 0.01f, transform.position.z);
C# is not Python
I've never used python in my life ;-;
wherever you wish to have logic that runs based on the if statement
then why are you using indentation to denote scope?
Cuz it kept bugging me about it being wrong
until I put them there
indents dont affect anything, its purely for style/readability
Alright.
if (Input.GetKey(KeyCode.Space))
{
// whatever logic inside here
}
but you should likely do more c# basics if you havent learned this yet
Alright I will.
script for weapon switch but it isnt switching
it randomly switches when i keep clicking
Why is it in on trigger stay?
that's a lot of GetComponents to do every physics frame . . .
i dont know it doesnt work if i do it enter either
so i should calm down with them and maybe it will be fixed?
it'll be more readable and easier to follow. if you need to access the same component mutliple times, cache it in a temporary variable for reuse . . .
ok
I get the impression that you have no idea whatsoever what you are doing. I would suggest going back to !learn until you do understand
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
idk i did this before i dont know whats wrong this time im just rewriting my code from the start
I'm pretty sure I've told you this before, but you need to debug your code to actually see what it is and is not doing
ok i will
Hello
I have a problem in input when i enter playmode the input names changes but the movement no
but when i change the inputs in the play mode it become fixed
how can i fix that?
help me?!
I appreciate that you are not a native English speaker but you are going to have to make more effort to explain yourself because I, for one, do not understand a word of what you have written
okay i will come in a few minutes
i think he is saying when he changes keybinds it doesnt work and he cant move. But when he changes the input in play mode it fixes it
does anyone have the slightest idea why my button wont work?
public class buttonScript : MonoBehaviour
{
private static int money;
public void Button()
{
Console.WriteLine("clicked");
money += 1;
Console.WriteLine(money);
}
public void Start()
{
money = GameObject.Find("money").GetComponent<money>().moneyInt;
}
}
doesn't even print "clicked".
what doesn't work? the money is not added? does the method run at all? also, you do not use Console.WriteLine . . .
To start with Console.WriteLine does not work in Unity. use Debug.Log
dont know, nothing was printing
use Debug.Log instead . . .
im so used to using console.writeline smh
alright thanks ( @cosmic dagger @languid spire ) it works
problem was debug.log
no, the problem was Console.WriteLine. Debug.Log is the solution . . .
you know what i mean
how do I stop play if it's stuck in an infinite loop?
after some debugging the problem is that it isnt detecting my E key input
should i worry abt this
Set a break point where the infinite loop is likely occurring and attach the debugger.
that seemed to work, but editor is still frozen
Once the code executes that line, it'll pause and you can safely stop the play session within the Unity Editor.
Ah stopping the debug fixed it, thx π
okay
look @languid spire im using new input system and im using this to make a reblinding menu so the player can change his movement
and
i made this to change the inputs
but it doesn't work unless i change the action in the play mode
if i didn't change it in play mode it doesn't work
anyone know why this error might be appearing
ive checked multiple times but there seems to be nothing wrong
this is the code where the error is taking me
the line above is the one to worry about
oh yeah ive checked that already
what about the error though
the script isnt working
you are doing 2 new() there are either of them Monobehaviours?
no
try changing your StartCoroutine to
StartCoroutine(Method());
will do
why does public Money totalMoney; try to reference currentScript.totalMoney instead of Money.totalMoney
totalMoney is not a public variable of the current script. its a public variable of the Money script that I need to access
buttonScript is accessing totalMoney from money.cs/Money class
simple, you have not told it to
you have to specify which variable you accessing, if it's not local
we'll need more info than just this vague screenshot
just by giving a varaible the same name does not somehow magically link them together
sorry back on my main account, this is me
how do i tell it to
// buttonscript.cs
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
public class ButtonScript : MonoBehaviour
{
public Money totalMoney;
public void Button()
{
Debug.Log("clicked");
Debug.Log(totalMoney);
}
}
// money.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Money : MonoBehaviour
{
public int totalMoney = 11;
public Text moneyText;
private void Update()
{
//Debug.Log("updating");
moneyText.text = "MONEY: " + totalMoney;
}
}
by using a reference to the instance of the money class you want to use
so, im trying to reference totalMoney from Money class so why can't i just do Money.totalMoney
because thats not the way C# works
what do i write instead
you've created a variable object totalMoney of Money class.
yeah
all you have to do atm is totalMoney.totalMoney
i did that but it didnt work. let me recreate it so i can get the error
"didn't work" is too vague.
yeah... thats why i said give me a sec to recreate it to get the error
I'm not going to write your code for you but I would suggest you change
public Money totalMoney;
to
public Money money;
and set the reference in the Inspector
then you can do
money.totalMoney
just get the error and update, no need to give a blow by blow update π
public void Button()
{
Debug.Log("clicked");
Debug.Log(totalMoney.totalMoney);
}
``` prints `UnityEngine.Debug:Log (object)` which isnt the value
and you probably should learn some more OOP 
i'll give it a shot
public TotalMoney money;//Reference from the inspector``````cs
moneyText.text = $"Money: {money.totalMoney}";```
i've heard OOP is bad for unity so
Β―_(γ)_/Β―
Do you know what OOP is?
i suggest you to flip off anyone who said that
does unity have the capabilities to let you create a mega script that has everything instead of multiple smaller ones?
tbf OOP is bad for any system if you don't know wrf you are doing
You'd be surprised how many things people will say is bad. Either from overexaggeration or just repeating what others have told them
If they didnt tell you why, dont listen to it.
probably... ??? 
but then you better be off to some other means of game development, i guess
A single giant script isn't preferred over multiple small scripts due to managing issues.
would a large script not be easier to manage?
Absolutely, if you want to take that road into coding hell
fuck no
Also unity isnt related to that, you can create your classes however you want. Unity doesnt care
you should not hand off grenades to monkeys 
when i use lua its usually easier to make a module script with all ur shit in it and run everything from there. if you need to make scripts, u can just reference main one for data. i assume c# isnt like that
unless, of course, you have something against monkeys
I have no experience with LUA so I could not possibly comment
dont learn it. its useless
I mean, were you creating games in lua? Sure main functionality or utility functions make sense to throw in 1 area. But the actual game logic? Hell no
i was and i was running all game logic from a single script using couroutines and threads
LUA is for smaller scripts - I don't think it a language for anything large which is where you need to break things down. But in C# you can have a static class or Singleton to maintain your core data if you really want
and it worked
I have no intention to, although I do program in many non OOP languages and it is my experience that you eventually end up implementing a faux OOP within them to make sense of them
Or course itd work, this isnt a question of will it run. It's a question of how much will people hate working with u after seeing a 3000 line script named Game.cs
//buttonscript.cs
public class ButtonScript : MonoBehaviour
{
public Money money;
public void Button()
{
Debug.Log("clicked");
Debug.Log(money.totalMoney);
}
}
``` still prints `(object)`.
```cs
//money.cs
public class Money : MonoBehaviour
{
public int totalMoney = 11;
public Text moneyText;
private void Update()
{
//Debug.Log("updating");
moneyText.text = "MONEY: " + totalMoney;
}
}
serious question though, will it impact performance in any way?
screenshot the ButtonScript inspector
i mean, in the environment i was in that was expected. Multiple scripts was bad. you are expected to create it all within a single script
less is more
certainly not the case with c#
Then the environment you worked in was backwards
because of the rhar is not the inspector of ButtonScript
that was my roots so its hard to break out of that
oh
do i have to reference stuff in the script properties??
guh
no, that all looks fine
money is undefined
do you need Money to be MonoBehaviour?
like, do you intent to create GameObject with this script?
if not, then you probably be better without Monobehaviour parent in Money
not according to your screenshot unless you have mutiple ButtonScript instances
You're likely referencing something else in the on click event and not the instance with the proper reference to money.
If we're talking about like nanosecond level then I'm not sure. But overall no assuming it's the same logic just in 1 class.
Which also I should mention doesnt really apply in unity because you wouldnt be able to separate components then and attach them
this is what im trying to do. clicking the buttons +=1 to money int which is a property of money.cs which is under money display text
ur money dont show?
its not finding the variable to add
This isn't really a coding issue anymore but rather an issue with using the Editor Inspector in regards to referencing. Make sure you drag the correct scene objects into each reference field/slot.
send text in inspector
do you know why button() isnt showing up as a function?
public class ButtonScript : MonoBehaviour
{
public Money money;
public void Button()
{
Debug.Log("clicked");
Debug.Log(money.totalMoney);
}
}
U dont need second script
im not going to manage buttons and money in the same script
Which object did you drag into that On Click listener field?
because you have dragged the script in not a gameobject that has the script
Did you simply drag the script from the asset fold or the scene object with the component script?
yeah
editor do not allows not scene Monobehaviours to be referenced that way
Drag the scene object with the component script.
i added it back to game manager. i tried to cut out game manager but yeah unity doesnt let you do that
man, you really need to take some time and learn the basics of Unity otherwise your life is gonna be a world of pain
this is what im trying to do
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
wait a 5 min and i send solution
I'm not sure what you're referring to but you ought to definitely be able to drag and drop objects with the appropriate component into fields. There is likely some miscommunication.
i dont even know what the issue is at this point. everything is defined and code is clean
button, game manager, money display, button script, money script
Are both of the objects in the scene?
man, look at the line abnove ffs
object is just where it is coming from. it's working fine
its not printing the value
yes it is
the value is defined as 10 which unity acknowledges in properties
wtf do you thing the 10 is ?
why is it not printing 10 then
it is printing 10
its printing object
what do you think that is? π
no, it is printing 10 which is coming from a Unity Object
put ya glasses on
it was about Monobehaviour script being referenced not from scene by another script in editor. It not let's you to drag'n'drop script from hierarchy
your lack of attention, you clearly understand 'clicked' is being logged out.. then completely ignored the 10
is there console plugins bceause i dont like this display if you couldnt tell
Yes
I use Editor Console Pro, it's much better than the default IMO. But look on the asset store at the millions of available ones.
I have Weapon : Equippable : Item and Armor : Equippable : Item
Does this not work for Weapon and Armor?
GetComponentInChildren<Equippable>();
why is Equipable in your chain twice?
yeah it's actually Weapon : Equippable and Armor : Equippable and then Equippable : Item
Do you mean you have ?
Weapon : Equippable
Armor : Equippable
Eqiuppable : Item
yes
I think he meant equippable inherits Item and both weapon/armor inherits equippable.
seems a bit besides the point
It matters, because we're trying to understand what you actually have, you wrote it in a weird way
I would expect the get component to work
you probably want
Weapon weapon = GetComponentInChildren<Equippable>() as Weapon;
If it did not work, you should explain so else just try it out and ask why it isn't working whilst providing more info (if it doesn't).
hmm yeah it works, guess I have a logic error somewhere then
if u need
using UnityEngine;
namespace Clicker
{
public class ButtonInput : MonoBehaviour
{
[SerializeField] private Bank _bank;
[SerializeField] private int _moneyPerClick = 1;
public void PressButton()
{
if (_bank != null) _bank.AddMoney(_moneyPerClick);
}
}
}
using UnityEngine;
using TMPro;
namespace Clicker
{
public class Bank : MonoBehaviour
{
[SerializeField] private int _money;
[SerializeField] private TMP_Text _moneyDisplay;
public void AddMoney(int moneyPerClick)
{
_money += moneyPerClick;
_moneyDisplay.text = $"M: {_money}";
}
}
}
okay, I need a bit of help people,
I'm doing a tower defence game but the pathfinding of the enemies keep putting them on lines
and having a wave of killer insects on a straight line is quite... weird
do you guys have any idea to how to make them spread?
while moving to the target position
You may want to provide your current code (basically what you've tried) and an illustration if possible.
I mean, the code is basicaly, get the current navmesh pathfinder => go to the next position on the waypoint array
!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.
βοΈ that's how to share code
the comments are in portuguese but I belive it's quite simple to understand what I'm doing
You're probably giving them all the exact same destinations, rather than having a buffer around the node position
and spawning them all on the exact same point
Maybe have them walk towards the target but with some offset relative to their current offset and the center (where they'd normally be lined up). An easier solution would be to have their renderer on a child that's offset to the parent and move the parent - the parent would still be on the line but what you'd see would be then offset.
Hmmmm, interesting
they are spawned in diferent places but always endup making a line as the paths converge
they all have a specific ID for the path from a earlier attempt I had to fix this, maybe I can make so that this offset is based around that
adding a random value with a specific seed for pathoffset
gonna try that
because you give them all the exact same point to head towards
yeah, but they kinda have the same point to go, just a very long way to get there
I don't have many ways of changing this part of the code, maybe making them go into diferent positions on the end destination, but the end destination must be tha same for all of them
yes, lol, so add some variation to the points..
with some exeptions, my problem is the path that they make, I already know they gonna have the same path becouse of this, so I need to find a way for them to create some variations
instead of giving them all the exact same positions to head to (and then wondering why they're in a straight line!).. add a random value to the x,z of the pos.
my idea was something similar, every time they get to a way point, while they are at a certain distance, instead of going directly there, they go to a offset based on a random number
If you do that, they will still end up getting into a straight line and then diverging. Seems an odd way to do it... just work out the offset before setting their next target position
one option you could try
A
WayPoint[] A1
WayPoint[] A2
WayPoint[] A3
B
where you chose a random waypoint from the next array at each stage
hmmmm, that is a interesting position, but don't this endup being the same thing I'm trying to do now, but with specific waypoints instead of a random offsetpos?
not really, no, you are much less likely to get a procession effect
depends how you define your waypoint positions
hello, im trying to create a script where all of my game objects will be visible inside camera no matter how far they are by changing camera's orthographic size. that functionality is working but i cant figure out how to add margin to this feature so i can avoid gameobjects hiding behind UI and be visible inside an area i want them to.
for example i want to add a 50 pixel margin from the edge of the screen. but this margin isnt consistent and keeps decreasing as objects go further away. help pls
https://hastebin.com/share/dumogahuqe.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
okay, the random pos offset worked, thank you guys for the help
what's this got to do with code?
I honestly dont know where to ask about layers
sure thing, thanks
How do I get a clone's Parent?
I want to destroy the object, but the clone is a rigidbody
public Rigidbody ball;
Rigidbody clone;
if (Input.GetMouseButtonDown(0)) {
if (mouseclick == true) {
clone = Instantiate(ball, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector3.forward * 50);
clone.name = "tiro";
}
}
Destroy(clone, 2f);
I want to destroy this clone's object, how do I do it?
you need to destroy its gameObject not the Rigidbody component
exactly, but I don't know how to get its GameObject

transform.parent mby
read my message very carefully, i've given you a hint. then go look at the documentation for the Rigidbody component and see what members it inherits
it has no parent. and, again, they need to destroy its gameObject, not a transform
he wants to know how to get the clones parent so i assumed theres a parent
they are misunderstanding the hierarchy. we can clearly see that no parent has been assigned in the code they showed.
okay
they also clarified what they meant with ["I want to destroy this clone's object"](#π»βcode-beginner message)
thanks
I found a way here
How can i reach these two values through code?
took me 10 seconds to find the answer on google https://docs.unity3d.com/2019.4/Documentation/ScriptReference/RenderSettings.html
ambientIntensity and reflectionIntensity property?
ambientintensity and reflectionintensity sound like the ones you have underlined in red
why did u edit ur message lol
i edited before reading ur reply, sorry
so those are cool but still how do i get to the rendersettings in code?
Just RenderSettings
did you try RenderSettings.ambientIntensity = 0?
#π»βunity-talk This is a code channel
oww, im extra dumb today. i tought i need to reference something first to access that path. thanks
Apparently if I use .FindWithTag(""), MonoBehaviour doesn't let it happen?
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public GameObject CamFollower = GameObject.FindWithTag("CamFollower");
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = CamFollower.transform.position;
}
}```
You can put that method in the field initializer
I don't know what that is
when you initialize a field
that gets created normally when a class gets new()
unity takes care of this on its own, so you cannot run MB method there
the error message literally tells you how you can resolve this error too
I thought it just said I can't do it
it said you cannot call it where it currently is, and gave you two options where you can call that method from
Oh I just need to put it in start?
just to be clear, only the assignment.Not the whole line
nooo
oh wait..
now its local..
oh ;-;
define it outside the method, assign it inside the method
do you know what assignment is ?
Not really, But let me try it outside of everything
you should start with the beginner c# courses pinned in this channel
instead of guessing, why not say "No I dont, can you tell me"
Well sure.
Like I said I don't, And then tried something extra (guessed)
well this isn't a guessing game lol
its precise science
things mean things
= is symbol for assignment
Alright.
Also I'll try that out when were done (if we will be done with an answer)
well then i won't be helping you any further. good luck
Instead of asking y'all everytime I don't know a thing about c#
Sure I guess
this is literally what you are currently doing. you need to learn the fundamentals of the language
also even if you solve this, this wont give you a good camera follow anyway.
You should just use Cinemachine here for easy camera follow π€·ββοΈ
I was making a 2D platform game, I wrote a code to open the relevant scene when you press the levels, but it doesn't work, can you help? Error: 'Level1' couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
To add a scene to the build settings use the menu File->Build Settings...
UnityEngine.SceneManagement.SceneManager:LoadScene (string)
LevelMenu:OpenLevel (int) (at Assets/Scripts/LevelMenu.cs:12)
UnityEngine.EventSystems.EventSystem:Update () And even though I adjusted the building settings, I have this problem.
can you show the build settings with the level β in question β added?
show your build settings page
where is the -
that's not correct . . .
right now your level shows up as Level0 for example
"Level" + levelId; would be Level1 . . .
first photo the player1 has an rb2d component and the second one only has a box collider
why the collision detection works only when i use the dynamic rb2d
you should not use translation to move a rigidbody if you want accurate collisions
not even the kinematic one
and if i don t want to use a rigidbody and still get collisions
kinematics don't collide into objects but others collide into it
for kinematic, use Rigidbody.MovePosition . . .
you would painfully have to use physics queries or positions based..
if you're using physics queries you mind as well use rigidbody
then you need raycasts and physics queries . . .
i tried to use a kinematic rigidbody and still doesn t print nothing in the debug menu when it collides
why
i just told you why
Triggers are not collisions
Collision only happens with dynamic bodies
just stick to dynamic rigidbody and use .velocity
and i have another question
easiest way to do collisions and paddle of your game
i tried to make a platformer and made a dynamic rigidbody but my jump didn t work
That's not a question that's a statement
yessssss
depends how you were jumping . . .
i was using velocity to move left right and add force to jump
when you set velocity just exclude the y
and addforce will work
.velocity = new (myMovingHorizontal, rigidbody.velocity.y)
for 2D you can do myRb.linearVelocityX = myMovingHorizontal;
velocity should not have fixedDeltaTime multiplied into it btw
also your code is trying to read input in FixedUpdate which is wrong
input must be read in Update
heyyy really dumb question
if i create a new list
new List<whatever>();
^
what goes there?
Nothing usually
do unity projects save to the cloud?
should have it multiplied outside of it
reading input (like that) in FixedUpdate will skip (miss) those frames . . .
neither
what can it be used for?
Have you checked the documentation? It's all spelled out.
when do i use time.deltatime and time.fixeddeltatime
when converting a per-frame quantity into a per-second quantity
it is confusing bc without this everything works fine on my computer
velocity is already per-second
where can i find if something is perframe or persecond?
it's not something you "find"
it's about understanding conceptually what your code is doing and what your variables mean
btw you should configure your IDE π
ahh there we go
Either nothing, an IEnumerable, or an int
Thank you for your help. How can I solve it? I don't quite understand, sorry.
thanks for the help
ok, what is the name of your level that you added to build settings?
@river halo do you have it?
strings are very much sensitive to casing, spacing, and ofc missing characters lol
"I am a string"
Is not the same as "i am a string" etc.
This should work rigth? but this happends?
it should work to do what? We don't know what targetLimb is or what this joint is attached to or anything.
what should work? you should always explain what is expected vs the actual behavior that occurs . . .
I added 3 levels level-1 level-2 level-3 Do I need to add these to my code?
my friend, answer the original question Random asked you
yes added
ok. now, when "Level" + levelId; is combined, what is the output of that string?
yea
you mean like abstract, virtual and override methods? sure . . .
can someone help me real quick, i want to make it so my player cant move/has limited movement mid air https://pastebin.com/syiKcBqx, im not much of a coder and need a lil help
first you should explain what is happening vs what you expect happening.
Oh mb i have put the targetRotation script on every bone in the active ragdoll to the coresponding in the None active version. but insted of copying the rotations it looks like its self imploding
@river halo #π»βcode-beginner message
store it inside a variable first then Debug.Log it
string myResult = "Level" + levelId
Debug.Log(myResult)
its just an fps controller but when jumping i can move freely when mid air i want to make it so i cant move when mid air or slow it down so i cant move as fast when mid air
break down the problem into smaller easy to solve ones.
you already have a Grounded variable since you are working with character controller. Check if you're grounded when moving and adjust accordingly
you should be able to tell already. you're adding the word Level plus the value of levelId. if you know what value levelId is, then you just combine them together. E.g., if levelId = 1, then the output is Level1
now, if that is true, you said, you added level-1 to the build settings, correct? is level-1 the same as Level1?
I pressed level 1 and it said 1
you see it printed Level1
is that the same as Level-1 ?
I understand
perfect. now look at that string: it says Level1. is that the same name as the level you added to your build settings?
as navarone mentioned earlier, every single character and its case in a string must match for it to be equal . . .
Hey guys, so my player has a boxcollider2d and is able to to movement like walk, run, slide, and crouch. The problem I'm having is that when there are platforms that the player can crouch/slide under and then stand up, the two box colliders clip into each other, which results in the sliding glitch throughout the whole game until I reset the game. Now I know that I can prevent this by detecting if there is something above the player's head, but that is something that I will be getting into later. What I want to know is if there is a way for the engine to not keep this glitch after getting out of the box collider clipping so that way, if there ever is this type of glitch in the future, at least it wouldn't keep that glitch through out the whole game.
does rigidbody.moveposition collide with walls the same way as addforce does? i've been told on this discord that it shouldnt be used because it doesnt collide properly with stuff
You can cast a raycast
that makes it not able to stand up
you need to check if there's room to stand up before standing up
u probably want GetKey
GetKeyDown is only true for the first frame you press the button. and since you set vertical to 0 every frame, you overwrite that value you assign. also you move the same direction no matter which button you press
look into using GetAxisRaw instead of querying each key individually. it even includes the 0 value when neither key is held
btw you can just do
float verticalSpeed
...
verticalSpeed = Input.GetAxisRaw("Vertical")
ohh ok, idk what raycast is, but ill look into that. I just wanted to know if there is a way I can get out of this glitch instead of having it the entire game if I ever get it somehow.
i know but i had in my head the idea to make 2 public keycodes up and down
alrighty
bc i have 2 player and to player 1 to assign w and s and to player 2 to assign up and down arrows
so i don t make 2 scripts
you could just make two separate axes
I think just casting a ray cast up and set a Bool to "can stand up" and if the ray hits something it will be sett to false and if not True
i need to do some documentation about axes and buttons
@pine furnace https://docs.unity3d.com/Manual/class-InputManager.html
ah ok yea, maybe using that will be easier for me
easier than.. what?
Question: Is it normal to create a service for methods like set, get, update, clear, and other operations related to a single item, such as a car? I want to retrieve data from the save system (SaveLoadSystem) on request for each car, meaning getting the same class but with different data. Additionally, there are other data about currency that I placed in a different service dedicated to currency data exchange. These services are unrelated to data saving. Is an interface implemented that collects all the data from the services and then saves it in a specified form or type? I thought about generalizing everything, but is this necessary (or is it needed)? Is it better to have one interface for each service required in the application as needed? Hmmm...
Probably want to do a spherecast (or circle if this is 2d) that is the width of the player.
A ray is infinitely thin, so it may miss something above you while the actual collider does not
ahhh ok. Thank you for that! I'll keep that in mind.
hi guys, how is this type of inventory created? the one that has buttons that switch to each category of the inventory? Is it made with actual Unity Buttons or is there a UI Element that I dont know?
that's just a tab view where each view just filters the items shown to a specific type
what do you mean with "tab view"?
a view with tabs to switch between different views
and infact, that doesn't even need tabs. just buttons that literally just filter what is being displayed
so maybe I can have a component that enables and unables the different Pannels?
depending on the Button you click In
well that's what a tab view would be. but again, this doesn't even need to be one. it just needs to filter which items are displayed
It is filtering what displayed, not opening tabs
oh, okay I see, my intention was to use different tabs, so I get it now
You basically can assign a specific type to every item and then display βem in the inventory depending on the active filter, if you want that
okay, thanks a lot
does anyone have a suggested video that helps with creating first person movement and mostly gets straight to the point?
"the point" of tutorials are to teach you how and why you do certain things. if you are just looking for a video that just gives you the code to copy then good luck π
There are different types of controllers, so suggesting you a random one might not fit for you
ill just watch a bunch and see what overlaps until something clicks in my brain
the click method.. it works.. results may vary
they are absolutely videos like that to post the entire code in the description.. but what do u learn from that??
https://www.youtube.com/watch?v=PmIPqGqp8UY&ab_channel=AcaciaDeveloper i liked this when i was learning he stops and explains a few things that are important
I am creating a 2D sandbox game within Unity using Alteruna for multiplayer. I have a script that uses a sprite renderer to render everyone elses curser on peoples screen so they can see. Currently though all cursors from other clients all go to the main client mouse position. How would I keep the mouse position different from everyone elses then sync the positon?
TLDR: How to do client sided move sprite onto mouse position then sync using Alteruna?
thank you π«‘
its been a while since ive worked in unity, and i was a beginner then, so ive kinda just went back down to 0 in terms of knowledge
i mostly remember my way around the UI and such but lots of things just sorta disappeared over the past year or so
happens..
hey, whenever i try to create New Project i get this error, is there anything i can do?
check the !logs
check the hub !logs
double kill!
thanks ill do my best β€οΈ
void Start()
{
Debug.Log("Start");
}
void Update()
{
if (Input.GetKey(KeyCode.T))
{
Debug.Log("T has been pressed.");
}
}```
Does anybody know why the Start debug runs but the Update one doesn't?
presumably this object gets disabled at some point
Are you pressing "T"
Or you're not pressing the T key, or the old input system is not enabled or... or...or...
Show a screenshot of this object's inspector while the game is running
ive ended up spending far too much time in blender now π
i mean im not good at it, prob cuz im not actually watching any tutorials but
i mean now i kinda get how map building works so π
but what does this have to do with coding questions?
nothing wrong w/ the code itself..
It also works when I remove the if statement
then its ur input.. do you have the old input system enabled
I don't even know what the old input system is
lol.. that means its probably still turned on
its the Input system, but older
edit -> project settings -> player -> other settings -> active input handling
It was set to old
I changed from old input to Both and now it works
very interesting
okay
what does that even mean..
You see i have a json string which is serialized
and instead of deserializing the string back to a object? class type
i am deserializing it back to JObject
Now my goal is to change the key name of every keyvaluepair<string, object?> inside the jobject i got
i dont know how to do that?
google aint documented about this
if i use a foreach loop like this
{
//if (kvp.Value is JObject)
{
}
}```
I can only loop and read the keys
not write them
i wanna mod a game so like i need to add guis with coding
Can't do that thew keys are immutable
the jtoken actually allow you to edit both the keys and values as well
but i dont know how to access them
not documented
creeate a new JObject and write the new kvp into it
tried
i failed
cuz i lack the complete knowledge of how json works
{
List<KeyValuePair<string, object?>> ks = new List<KeyValuePair<string, object?>>();
ks.Add(new KeyValuePair<string, object?>("paint", "this"));
jobj.ReplaceAll(ks);
string jsn = JsonConvert.SerializeObject(jobj, Formatting.Indented);
return jsn;
}```
i just wanna paint text by adding html color code within the keys to highlight them
just like how websites highlight their codes
i tried this
it failed
so i am kinda out of ideas how to achieve the result
you want to change the key name in what way? Can you show an example?
you do realize that this
ks.Add(new KeyValuePair<string, object?>("paint", "this"));
is nonsense
yea sadly
wait let me
JObject paintedJobj = new JObject();
foreach (var property in jobj.Properties())
{
string paintedKey = $"<span style=\"color: red;\">{property.Name}</span>";
paintedJobj.Add(new JProperty(paintedKey, property.Value));
}
``` try it but might not work
use spans for html
Is the goal here just to display formatted json with color coding on a web page or something
I think the correct approach is probably not to use JObject but instead write a custom NamingStrategy:
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_NamingStrategy.htm and then you add your custom formatting in ResolvePropertyName: https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_NamingStrategy_ResolvePropertyName.htm
This example shows how to use a special naming strategy with JsonConvert:
https://www.newtonsoft.com/json/help/html/NamingStrategyCamelCase.htm
I have an object which is a prefab that has an instance in the scene editor. If I delete the prefab, will the instance be deleted too?
You could probably also write a custom inherited version of JsonWriter:
https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_jsonwriter.htm and override this: https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonWriter_WritePropertyName.htm
see this visual studio
how it highlights the json
the whole json is like a JObject and has key value pairs
one the first 2 are keyvaluepairs<string, int?>
the 3rd one is a keyvaluepair<string, JObject?>
and the last one is from the 3rd key value pair JObject which has only one keyvaluepair<string,string?>
i just want to somewhat achieve the same color highlight
by added this arround the string key
<color=#FFFFFF>Key</color=#FFFFFF>
the instance will not be deleted but it will show as a broken prefab reference
sorry for the delay
yes see my answers above for how to best do this
Here #π»βcode-beginner message and here #π»βcode-beginner message
let me take a look at it and let you know
Would this break anything to do with the object? Could I remove the prefab reference so it's just a normal object somehow, it being a prefab is actively bad in this case
You can remove the prefab reference yes. Just right click on it and go to -> Prefab -> Unpack Completely
Thank you
I want to change items in hand with mouse wheel or numbers on keyboard but the mouse keeps overwriting the numerical inputs
well it will, think about what happens if NO key is pressed
how do i change the index of an array item?
you move the item to a different location in the array
yes but how do i do that? sorry if this is a dumb question i just couldnt figure it out
what like
int[] a
a[2] = a[0]
i.e. copy index 0 to index 2
wouldn't that then remove index 0?
no
arrays cannot remove elements
they are fixed sizes / length.
Also no way assigning would remove ANY element
I mean look at what your else does
I know but I dont know how to rewrite it to make it not do what it does now
that shouldn't be an unconditional else it needs to be like else if (mouse input is not 0) (pseudocode of course)
else happens no matter what
you only want it to happen when there's mouse scroll input
I felt like an idiot before but this is so simple am a few levels even beyond that
I recall someone using keycode int cast inside an array to make this easier than a giant if else chain
I've seen things that were way dumber than this, don't worry.
also yes to this
anyway thanks for enlightening me :D.
e.g.
for( int i = 0; i < 9; i++) {
KeyCode k = (KeyCode)((int)KeyCode.Alpha1 + i);
if (Input.GetKeyDown(k)) INVindex = i;
}```
This is much better than 8-9 if statements^
I have to save this cause I keep forgetting it π
Ok it needs to be this to compile (also fixed above):
KeyCode k = (KeyCode)((int)KeyCode.Alpha1 + i);```
hey suppose i have something that takes arguement as object?
how do i specify its object type
can you elaborate? because it sounds like you want a method parameter and for that you just . . . use the type you want for the parameter
foreach (var kvp in jobj)
{
KeyValuePair<string, JToken?> keyValue = new KeyValuePair<string, JToken?>("<color=00FF08>" + kvp.Key + "<color=00FF08>", kvp.Value);
obj.Add(keyValue);
}
now the arguement it takes is this JObject.Add(object?)
ah so this is a continuation of a previous conversation that i don't feel like going through to understand what you are doing or why
and i am giving it JObject.Add(KeyValuePair<string, JToken?>)
why??
because i simply don't want to. someone else who is more familiar with whatever you are doing or who wants to read through that previous conversation can help you
thanks for the help
where do i ask for help for lighting problems?
Is there a way to 'block' a gameobject from beeing pressed until an animation is finished? 
i mean blocking as in the player cant click it again
disable it
How are you handling it being "clicked" in the first place?
if i disable it doesnt it get unloaded basically?
we don't even know if there's a script involved yet
do you want the honest awnser? cuz it's super dirty haha
component
wait one sec
yes I want the honest answer of course
because it's the only way to answer your question
what was the command for the linking code?
!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.
ah mb
its all scripts/components, even unity built in buttons. you just set whatever handles the click component.enabled = false
so i disable the script?
Use an animation event to set a bool true/false and check that bool in this code
or use a StateMachineBehaviour
i see
this can be annoying to change. i think it would be better to play the animation, start a coroutine, get the clip length then wait for it to finish in coroutine
basically im gonna check if an animation is playing, if not, it goes into the if (animator != null) and lets me play it
Hello, I am making a third person controller an I want to enable and disable an input action for the mouse delta, whenever the Cursor.lockState changes from Locked. The problem is that there is no event for this change of state. How can I achieve this?
var clip = animator.GetCurrentAnimatorClipInfo(0);
var seconds = clip[0].clip.length;
yield return new WaitForSeconds(seconds);
use a bool to find this out
time to start. they are really helpful
Why are you using JObject and JToken when the types are known?
This is either overcomplication or you are too lazy to make actual classes, in which case I suggest you just stick to classes and serialize those
If it's neither and this object actually has multiple types then I suggest you split them. JObject should not be used like this
Is there not a way to check this before the input is processed? Maybe in the binding's processor?
Make a singleton "CursorManager" which allows you to enable/disable it and it will fire an event you can subscribe to
Event also goes in the manager
yea my bad
now i fixed it here
{
JObject obj = new JObject();
foreach (var kvp in jobj)
{
obj.Add("<color=#FF8800>" + kvp.Key + "</color=#FF8800>", kvp.Value);
if (kvp.Value is JObject)
{
JObject nObj = (JObject)kvp.Value;
string strn = paintKeys(nObj);
JObject mObj = JsonConvert.DeserializeObject<JObject>(strn);
obj["<color=#FF8800>" + kvp.Key + "</color=#FF8800>"] = mObj;
Debug.Log("it reached here");
}
}
string str = JsonConvert.SerializeObject(obj, Formatting.Indented);
return obj.ToString(Formatting.Indented);
}```
but i am still having one last trouble
You fixed it but I still see multiple instances of JObject
you see i am checking here if the value is again a JObject
if (kvp.Value is JObject)
how can i know if the Value is an array
Why is this taking a JObject to begin with? Where is this code from?
i wrote it myself
Either way it doesn't matter, your code always expects the same things so you should deserialize the JObject into a readable class before you do anything else in the method
Right now you are practically parsing and considering it's not varying data it makes no sense
i am just highlighting keys with colors to be shown
So is the point to just modify the keys of a bunch of key value pairs?
You should still be able to do what I said. It would save you having to constantly deserialize/serialize code
If the point is specific to a key then you should probably also just use an interface so that it can be abstracted to any key-value pair
modifying keyvaluepair is not possible
so i had to cast
https://discord.com/channels/489222168727519232/1265474997183320204 i am in a hard situation...
i am making flappy bird how would i immobolize the player gravity included without stopping time
gravity scale = 0
immobolize the player gravity
What does this mean?
the thing navarone said i meant that
I am having some troubles parsing JArray
Can you pls guide me?
whenever i use this foreach loop
the cast doesnt work
foreach (JToken ajt in array.Children<JToken>())```
i thought that JArray just contains child JTokens which could be parsed into JObject
so check what's the actual type of kvp.Value and adjust code to properly handle
also, can't you parse into a proper typed object instead?
its not a specific class which i serialized
I am making a text highlighter that could work for any json i give in as input
not sure that's how you should do it... but haven't thought about it
here is the complete code
{
JObject obj = new JObject();
foreach (var kvp in jobj)
{
if (kvp.Value is JObject)
{
JObject nObj = (JObject)kvp.Value;
string strn = paintKeys(nObj);
JObject mObj = JsonConvert.DeserializeObject<JObject>(strn);
obj["<color=#FF8800>" + kvp.Key + "</color=#FF8800>"] = mObj;
Debug.Log("it reached here");
}
if(kvp.Value is JValue)
{
obj.Add("<color=#FF8800>" + kvp.Key + "</color=#FF8800>", kvp.Value);
}
if(kvp.Value is JArray)
{
JArray array = (JArray)kvp.Value;
JArray narray = new JArray();
for(int i = 0; i < array.Count; i++)
{
Debug.Log(array[i].Type);
//JObject aobj = (JObject)ajt;
//string astr = paintKeys(aobj);
//JObject naobj = JsonConvert.DeserializeObject<JObject>(astr);
//narray.Add(naobj);
}
}
}
string str = JsonConvert.SerializeObject(obj, Formatting.Indented);
return obj.ToString(Formatting.Indented);
}```
and I don't get what I'm doing is right
it works but fails only for JArray
where exactly does it fail actually? on which line?
only for JArray
{
JArray array = (JArray)kvp.Value;
JArray narray = new JArray();
for(int i = 0; i < array.Count; i++)
{
Debug.Log(array[i].Type);
//JObject aobj = (JObject)ajt;
//string astr = paintKeys(aobj);
//JObject naobj = JsonConvert.DeserializeObject<JObject>(astr);
//narray.Add(naobj);
}
}```
i cant seem to parse it correctly
exact line
take it here where i cast the JToken
like, what's the problem... because the cast can't be, as you've already made sure that kvp.Value is indeed a JArray
JObject aobj = (JObject)ajt;
yea its a JArray
but i am trying to get like array[i].get as magic JObject
but it may not be a JObject... it bould be a value or array, no?
yea i debugged its type
its quite tricky
cause it shows twice that its type is a Object
and 99 times its an int
and i cant figure out how it works
the component of the array
not the array itself
the component like array[i] in loop
what's the type of array[i]? I assume it's JSomething that's parent of all the array and other ones, no?
its a simple JArray
wait let me give example
large code should be shared via links
the particle dosent turn off when Im in the air, can somebody help me?
oh
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
like this?
the array is JArray, array[i] is JToken, which could be one of several things... so you need to handle those, maybe you need to call the function recursively, or just deal with the JToken somehow, no idea
yes. also where is it supposed to turn off I dont see that in the code
now take this as example
"Cages": {
"Array": [
{
"Dogs": 2,
"Cats": 4
},
{
"Dogs": 6,
"Cats": 1
}
}
}```
its an array
the whole thing is a JObject
You parse the JObject and get key and values
i check if the value is simple text or is another JObject
i can do that pretty easily
but what Array does is that it has an array of JObject
like JObject[]
but when i try to cast it
it has JToken[]
it doesnt work
that just sets a boolean to false. What does that have to do with ParticleSystem
which can be JObject, JArray, JWhateverElse
yea
wrong link, thats the correct one https://hastebin.com/share/tahofubofa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and if it's not - it throws an exception
but it still fails
maybe
Yes I can see that. My question still remains though
If you mean freeze the player, you'd cache the velocity and set to kinematic
how
kinematic will freeze the whole rigidbody not just gravity, is that what you want?
yeah
