#๐ปโcode-beginner
1 messages ยท Page 702 of 1
Maybe I am doing it wrong, how do you do it
you've got playerprefs otherwise if you only need to store like a level index
show what you did and we can tell where it went wrong
I'd store data in a json and then load the json when I need it
I works kind of but it doesn't save everything
Like it saves almost everything, but it doesn't remember what other scripts do, I don't know how to explain it
I don't have the code, I tried it in a different project which I deleted a while ago, it's just before I try it again, I want to get it right
roughly
//save
string jsonData = JsonUtility.ToJason(dataToSave, true)
File.WriteAllText(pathToSaveFolder, jsonData);
load do the inverse
its that simple
There is no one objectively "right" way. It would depend on your project needs and personal preferences.
Neither of which we know, so we can't really give you the right answer.
I suggest: Google and find what ways there are. Then try them out or research their ups and downs and decide which one suits you better. Then try it out and see if it fits you for sure.
Alright, I'll try something and update you
Any more specific questions along that path can be asked in the community and you will likely get a better answer than to the current generic question.
Okay, thank all you guys anyway, I'll keep you updated
speaking of which Unity also had a resource on this
https://unity.com/blog/games/persistent-data-how-to-save-your-game-states-and-settings
Thank you Iโll give it a shot then๐ฅฒ
What is the difference between public and serialized fields?
public can be accessed by other scripts serialized fields are privates just shown to the inspector
generally better to keep variables private and use encapsulation to change / get them, though not like i do this myself 90% of mine are public :/
A serialized field is a field Unity serializes. Unity has a few rules for which fields are serialized. The type of the field must be serializable and the field must either be public or have the SerializeField attribute.
private variables are normally hidden in teh inspector
serializing it makes it exposed in the editor
but the functionallity of it is the same as a regular private variable
Is that why not all fields are serialized? What does it mean for a field to be serializable? Or does it just encompass certain types of fields?
hehe, 90 of mine are serialized privates (but i used to do the whole public everything until it was time to refactor)
probably only half of them for just this script :/
very nice lol
going from 10 to 177 (ignoring that half the lines are the [] thingys
i hope all those values match the inspector values ๐
nope not at all
i doubt even 10 of them are :/
๐ฌ i used to take screenshots and / or keep lots of recordings while working on my CC controller.. b/c lots of my values changed and i couldnt be arsed to set the defaults to match
now i have the default values branded in memory
it's just easier to change em here and not wait 40 seconds
ohhh cool those tabs are awesome
yeah little feature of Odin Inspector but when havign this many variables (theres another like 8 scripts kinda like this) having the object selected while in play mode brings me from 150 fps to 25 fps
I'm having difficulty overriding a value,and I'm having difficulty finding a solution online
I have a class called "weapon", with a line like this:
public Vector2 direction = new Vector2(1,0);
And I want to change this value in a child class called "DiagonalWeapon"
How would I do this?
weapon.direction = someValue;
should work fine
just make sure the weapon class isn't overwriting it back.. (like if weapon is setting it to something in Update)
thing is, if I do something like that:
{
Weapon.direction = new Vector2(0.71f, 0.71f);
}
I am told "weapon" does not exist in this current context
oh an inherited class
not sure how ud do that one
wouldnt it just be "direction" = then?
Hey i have a question. I have a lot of different tabs, and wich i need to modify every single each of them and their text. The only way i know how to do so is if i make a referencial value and configurate each single one of them, is this the only way? Or is there another?
Its ok for a code to have A LOT of values?
As in, will it cause issues? No it won't
but i mean, it wouldn't be like, too tedious or smt?
or unprofessional
idk
i mean, i just dont want my codes to suck
but if others proyects do it, then i guess i will not worry
if its inherited wouldn't u just change direction on the DiagonalWeapon class itself since its inheriting Weapon, it should have its own instance of the variable? not sure exactly what ur doing
but seems to work
the original script keeps the original value.. and the inherited script gets the new value (I set it in Start() for the example)
unfortunately, it defnitely isn't so easy. To get no error to be thrown, I placed that change in an Update, although it didn't actually change the behavior.
Typically you'd use constants instead of "magic numbers"
if that is the question
for text however, it's fine I believe
what do you mean constants
and what about an army of bools
like
a staticObject that stores a bool per enemy/npc that is set true when you met/kill it
and by so, if that value is true, then it would make that specific button in the Codex go setActivate = true
could probably do something like that w/ a function codex.Discovered(enemy); and not have any booleans
Well, it compiles. Let me show you where this value is actually used, maybe that can help?
As unforutnately the "direction" of my projectile isn't actually changing
ya, i think some context would help greatly.. altho i may not be the guy to help b/c i dont use inheritance that often
so im probably not the best person to know.. but the more info u provide the better for anyone that sees
... how?
like ^ have the codex make the button visible or not or whatever
another idea that i had but wich is slighty paradoxic is having an int, if number is higher than X, display some tabs
issue is, i should present all stuff in order, or else it would "spoiler"
u pass in the enemy when u meet or kill it..
the codex takes the enemy.. finds the appropriate button.. does things to it
Here, I have this script called "PlayerAttack" that has a list of objects that have "weapon" class scripts attached.
The only place I can find in it where "direction" is referenced is here:
{
//This is where the weapon is rotated in the right direction that you are facing
if (weapon && canAttack)
{
if (weapon.weaponType == Weapon.WeaponType.Melee)
{
weapon.WeaponStart();
}
else
{
GameObject projectile = Instantiate(weapon.projectile, weapon.shootPosition.position, Quaternion.identity);
projectile.GetComponent<Projectile>().SetValues(weapon.duration, weapon.alignmnent, weapon.damageValue);
projectile.transform.localScale = new Vector3( projectile.transform.localScale.x * (scale.x / Mathf.Abs(scale.x)), projectile.transform.localScale.y, projectile.transform.localScale.z);
//projectile.transform.localScale = new Vector3(projectile.transform.localScale.x, projectile.transform.localScale.y, projectile.transform.localScale.z);
Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
if (player.transform.localScale.x > 0f)
{
rb.AddForce(weapon.direction * weapon.force);
}
else
{
rb.AddForce(new Vector2(-1,0) * weapon.force);
}
}
StartCoroutine(CoolDown());
}
}```
You can ignore the "melee" secion, I am not using it
but how specificly? i mean, do you mean by killing the enemy the tab should be turned to true?
And the projectile currently shoots horizontally, as the Weapon class direct (the vector direction for the default Weapon class is [1, 0])
wait, i got it.
I think it's that else, add force step.
yeah, I can shoot diagonally to the right now, at least!
I think that's it
so like for example ur enemy could have a ID number or something that corresponds to the button that represents it
public class Enemy : MonoBehaviour
{
public int codexID;
}```
when u meet it or kill it or w/e you'll probably have a reference to it..
soo you could call a function from the CodexSystem and shoot that reference over to it
```cs
public void Unlock(Enemy enemy)
{
if (unlockedEntries.Contains(enemy.CodexID)) return;
unlockedEntries.Add(enemy.CodexID);
// Enable matching button
codexButtons[enemy.CodexID].interactable = true;
Debug.Log($"Codex unlocked: {id}");
}```
then the codex script would just check if its unlocked already.. or interactable already and if its not it does it..
i mean thats just a simple example. but Functions/Events and stuff can do things directly without having to check abunch of bools or something
oh, i think makes sense, well, thanks
no problem.. it takes a bit to get used to that kinda workflow tho..
when i first started i'd use bools for everything.. especially inventory..
hasPistol, hasShotgun, hasBlueKey, hasRedKey
and it would end up with long if,else statements
now i just make a class called Key for example.. give it an ID or a Color.. then i just make a list of those..
thanks @spawn ! I got things working as intended now!
run thru the list.. checking the colors.. instead of a bool for each ๐
wait, how do i reference to codexButtons?
like this?
public GameObject[] codexButtons;
i mean so it get the numbes for the enemies's IDs
yea
an array of buttons would work
with each index meaning a different creature or w/e
oh, well, thanks :3
np ๐
yea, its whether or not the button is greyed out and/or clickable or not
cool, thanks
just as final question, the Unlock function must be on a StaticObject, right?
wouldnt need to be.. makes it easier tho
i mean for make this permanent
as long as u have a reference to it you could just call it
codexReference.Unlock()
but a static class or a singleton would make it more universal.. (like a game manager)
yeah, i mean, for make it permanent
cuz i need it to be permanent after all
ya, id go ahead and make it a static class or a singleton then...
have all the logic you'll need from the codex there in the class
and itd be easier to call it from anywhere and from anything..
thanks :3
u could have like HasEncountered(Enemy enemy);
HasKilled(Enemy enemy); etc etc
u could even simplify it and just have those methods take ints.. if the monsters or w/e will always have the same ID number..
that way it wouldnt even need an enemy class or anything.. just a number
HasEncountered(int monstersID) or something..
but i think u get it ๐ just gotta work it all out now
well, thanks a lot :3
hi, with this code, the lerp is completing rotations long before timer is equal to 1. I'm honestly clueless as to why the fuck it's doin this
Do the logs show timer is increasing at the rate you expect?
timer goes from 0-1 in a number of seconds roughly equal to usespeed, takes the lerp ~1/10th of that time to complete
makes 0 sense to me
Show the logs
Print other data that may be important such as the current position and rotation
And normally, you'd use the initial value as the first argument of lerp rather than the current value
I'm aware, trying to rotate from current position
all .50000 from there down
increased steadily before that
var init = ...
var target = ...
...
while(...)
{
... = ...Lerp(init, target, timer);
...
}```etc
That would not produce a linear interpolation then.
mmmm wise
yeah I'm fuckin dumb
figured out the fix I believe, gonna test it in a second
appreciate the help homie ๐
yup, works fine now
just had to move these outside the while loop so the position wasn't being updated every iteration
I know you are gonna ask me why would I want this, but, can a class hear to its own event?
technically classes don't get events, delegates get called, and it doesn't matter where the delegate comes from
Do u guys often use singleton? I mean, I get on just fine without it, and it does not seem to have a great reputation
good use of singletons is very useful yeah
There are too many cautions for such a basic pattern
says who
Does anybody own a gtag fan game?
overusing then is bad - then again, it's bad to overuse anything
not really the space for that
Is there a proper term for doing this kind of thing?
private float RemapLerp(float targetMin, float targetMax, float sourceMin, float sourceMax, float sourceVal)
{
return (Mathf.Lerp(targetMin,targetMax,Mathf.InverseLerp(sourceMin,sourceMax,sourceVal)));
}
its some sort of normalization.. I mean in a way
Remap is one term for it, it has many terms
i also just call it Remapping
i think ive also called it some kind of Scaling before too
i suppose that could get confusing with the map data structure though (or not, since c# calls it Dictionary)
(fwiw i don't think i'd call it remap lerp - you're remapping linear ranges, using linear interpolation to do it, rather than actually remapping the interpolation)
Why does the FindComponentInParent method check the current active object for the component as well as the parent? Seems like a silly thing to me.
If I have two Images for example, and I want to get the parent image from a script called in the child, this method does not return it
then call this method on the parent object instead...
Yes but I fail to understand why is this method implemented like that
If I wanted something from self, I'd just use GetComponent normally
because unity chose to do it like this. im sure if they implemented how you suggest, there would be someone out there complaining they need to call GetComponent and GetComponentInParent afterwards in their use case
tbh the answer is just an accurate name would be too verbose
Accurate name should be something like RecursiveFindComponent
either way tbh, i find that this method is something you should never be calling. drag in the reference you want. have the parent do the logic instead.
there are many options here that dont involve a child randomly trying to search a hierarchy which it shouldnt be doing
ok that sounds like something that searches down the children rather than up the parents
Tru
you should really try to put yourself in a scenario where you dont need this function. im not sure what you're doing here, i imagine this is dynamically adding children to a parent given that you need to call this rather than dragging in a reference
in which case you can still just pass the reference you want when the child object is instantiated
so you don't need multiple calls for trying to get strict parent components or own components
Very quick question: Should I be using float3 instead of Vector3 in monobehaviour code (even if it uses managed types, thus isn't Burstable) - is there any benefit to their performance?
I know in some cases you can enforce that certain checks are not being used with float3 (e.g. normalize vs normalizesafe), but are there other benefits
i dont like know this but im assuming you shouldn't be
on the basis that if there was a benefit unity wouldn't be using them
Well, Vector3 is an older legacy option, float3 came later with Burst. Though, the conversions between the two are presumably performance-intensive, so it's one or the other.
its not the legacy option, it is the option you use if working with gameobject. if you're using dots then you'd likely be using float3 more
anything like transform.position or scale are stored as Vector3
Yes, and the conversions between the two might be (according to the documentation) wasteful. But your code, that doesn't directly read from some of the builtin function, can use float3 just fine. And considering the mathematics library is better optimised than the legacy Mathf, it is in many cases beneficial
I don't think float3 struct itself is more performant than Vector3. It's the methods that operate on float3 (like those in unity.mathematics) that are more performant than those that operate on Vector3 (like Mathf)
I think it exists purely for the new math functions usable in burst/jobs
the mathmatics package has some nice additions though
I also make use of its Random struct when doing threading
https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.Random.html
beneficial how? you should profile and see if you even have a performance issue related to operations on Vector3 in the first place. i imagine itd be quite awkward especially for others if Vector3 and float3 were just randomly used in different files for the sake of hopefully saving nanoseconds
if you're using it in jobs or the mathematics functions, then thats different
Well, if one option is generally more performant than the other, it only makes sense to prioritise it going forward, rather than to rewrite the entire codebase when it's too late. It's not unreasonable to do such 'micro-optimisations', if it's only a matter of habit, since in this case it doesn't cost you anything to write Vector3 vs float3
when the performance gain is almost nothing, or could even be worse depending on how you're using the float3 (given it might have to be converted constantly) then id say it does not make sense at all. especially if you're working with others.
consistency > the false hope this will even be an optimization
performance impact of converting between float3 and Vector3 is like negligible. other things will matter way more.
yet it would still need to convert. the whole point is that they think its better to use float3 when they can, even if a micro optimization
theres always the argument where things could be better. "I could follow better design patterns" "I could optimize to save 1 cpu instruction". And it's always hard to argue against it because yes it is better, but it's a waste of time to even think about
surely on a level where the difference here would matter you should be profiling anyway?
my whole point here is that there is no difference or world where this even matters. if theres a reason to use float3, then it is because you're using it with systems that expect a float3 in the first place
aka like the things rob sent above
i basically agree.
float3 only exists because the functions that use float3 are more performant, and the functions that operate on Vector3 are not performant.
the question isn't what type do i use (float3 vs vector3). it's what library do i use (Mathf, Vector3 methods vs unity.mathematics)
is there a way to register custom virtual joysticks to new input system?
i have a working joystick that reads value, but i want to integrate it to new input system
but because this joystick cannot be properly invoked by on-screen stick component, i think i need to code it
it does cost you being able to use the rest of unityengine's api which works on Vector3
Bounds/Rect both still think with Vector3/2, and colliders and rigidbodies use those (or vectors)
you already are using UnityEngine, so you would just use those instead of branching off into mathematics where you gain next to nothing and lose interop with everything else
perhaps ask #๐ฑ๏ธโinput-system
ok
GetRoot or GetRootParent.. iirc uitoolkit uses this terms to get the highest parent in the hierarchy so proly that
that's what a root is, yes
getting a root or parents is indeed recursive, but so is getting children
Unity doing specialiation to mathf apis. They're hardware accellerated (il2cpp, nor sure if mono)
id say thats an even less accurate name than what was proposed, and what the current name is
use whatever suitable for the job...
we will have new fancy vector types once unity done moving to coreClr such as Vector<T> and Vector128/256/512. SIMD is so much easy in coreClr
Will be great but I presume il2cpp already improves on this (depending on the cpp compiler)?
bit of a silly question but the documentation on Color mentions all these crazy colours in the Color struct:
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Color.html
but I can only see the basic ones (red, blue, magenta etc)
am I missing something? haha
are you using 6.1?
yep, knew it was a silly question ๐
hi. i have an issue, this code of a codex is supossed to unlock InfoTabs depending on who calls it, but, the tabs are reutilized in 3 different categories depending on the int cassielIndexType. i mean, in UI are 5 tabs, yet, lets say you discovered 1 Leyend yet 3 Enemies. when cassielIndexType is 1, it must display 1 tab, but when cassielIndexType is 2, it must displays 3. Reutilizing the same 5 buttons
this is the code
{
if (unlockedInfo.Contains(codexID)) return;
unlockedInfo.Add(codexID);
codexButtons[codexID].interactable = true;
Debug.Log($"Codex unlocked: {codexID}");
}```
what you said is hard to understand but if you need to reveal or hide something depending on some int then each can have a list/hashset of the ints that will show it.
if contained, show, else hide. Is that sufficient?
you would need to loop over them all to update their visibility ofc
make sure to set docs to the version you're using
i think i have found a more easier aproach yet i dont know if exist, how i can make the objects inside a hashset to be activated or deactivated?
you would re design to have a list of a new type such as List<UITab> and then loop over and both access this "visibility" list and then set its visibility
a hashset is just a collection that uses hashing to disallow duplicates and provide fast Contains checks
Then i should make a list?
well yea, a list of your tabs
and the tab type can have its OWN list/hashset of the ids that can show it
... Wat?
You want to show some tabs depending on some input int right?
I mean
I want to show some tabs depending on an int and if discovered
Cuz the thing is
If the player finds something that adds info, like killing an enemy, it must make that tab activate. Issue, im reusing tabs, so when is on the category of A, it should display what discovered of A, if is category of B, display what discovered of B
The Hard part is the unlockinh and hiding tabs part
Then why does what I suggested not work?
Tab A (1,2,3)
Tab B (3,4,5)
2 -> Tab A
3 -> Tab A + Tab B
is this not what you need?
perhaps you need to better explain what "tab" even means, is it some UI button? is it actually some other UI that can show many elements?
True. I investigated english and i think tab is wrong. Is not tab the word
Is button
The categories are the tabs
Tab controls Ints
Ints controls info and Buttons
Do you mean the buttons can open different things depending on some category?
hi im trying to kickstart my game dev journey, and I was wondering if I should sign up for these short game jams get myself up and running, or shud I sign up for these longer game jams? is there a difference to how much work is required to build your game depending on the length of the jam? or is it just based on how much time you have available for yourself?
wrong channel
Yes
If this is the case, have some configuration to define what these buttons do depending on the "category", perhaps with scriptable objects using an Enum for the category
then you can configure what button a, b and c do depending on the category
The category is just an int
But the issue i have is the unlocking part
then use an int but there is a reason why enum exists (so we can give names to magic numbers)
then how does "unlocking" work or mean?
we just went from changing what a button does to something else
Cuz is the ingo part is easy
If (category = x)
{
If (index = x)
{
Info
}
}
whats index?
The info
The buttons only purpose is change index int
The info part doesnt matter
I think im overcomplexing stuff
If this is meant to be some UI list of objects the user has "unlocked" then this should be trivial, check this state when creating/updating the list
Unlocking is when the player for example kills an enrmy
An idea i had was that on each Category Block, it set all the UnlockedCategoryButtons to activate
But i dont know how
this might be insanely weird and simple, but it's making me loose my mind cus i can't figure out why it happens, so some help would be appreciated
i have this extremely simple code, that calls a game win function if the growTime gets above 1
if(growT > 1){
Debug.Log($"Won At {growT}");
GameManager.instance.WinGame();
}
but for some reason it detects the value, and even logs the value above 1, when in reality it's way below it
haha it must be
1.000399 > 1
It sounds like you hand make the UI with all these elements that represent all enemies right?
Something like this would ideally be dynamically made to show all configured enemies. It would also therefore be able to react dynamically to player data (such as changing visual state depending on if its 'unlocked' or not)
that's what i'm thinking too, but the value shows normally when i serialize it, and i use it for some visual stuff, and the visuals don't jump around when the win get's triggered
make sure growT is 0 at the start, before this is reached
I assumed regional diff. Even if not, it's still greater than 1
i mean i appreciate the context here but
it is that number when that log happens
period
what changes it?
a per frame addition
growT += growthSpeed * Time.deltaTime;
and nothing lowers the value
so even if it somehow jumps to above one, it shouldn't return to below 1, like it shows on the value property
are you looking at the right one?
this could absolutely lower the value :P, what's growthSpeedrn
The object logging the value and the object you are looking at in the inspector are different objects
i suposse
oh my god, ur so right, i'm actually so dumb
i have multiple ones with random speeds, and i forgot to disable the win logic, on the non important ones
damn ๐ญ
What you want is not hard really, if things are set up correctly its trivial to do what you want.
Even if you hand make the UI, if each "enemy element" has an id to specify what enemy it is, you can loop over them all and do what you wish depending on their unlock state.
Open ui to category -> refresh UI to show/hide/update enemy elements
thank you guys for the help btw :)
Logs never lie, the issue is always on the monkey's end rather than the machine
From there you can eliminate all possibilities that the number is anything but what was logged and all that remains is the simplest answer: it's two different numbers
my plan was that the enemy or events call the function and put on in the int parameter
but the thing is how i can do the refresh part
Its easy and I think you have this funny vision of some weird ass method of doing it that is falling apart
;-;
I make this kind of UI all the time and what you are saying is making no sense to me
If I have a UI that needs to show things (e.g. "unlocked enemies") then on Initialization I get all the enemy configuration entries and the player data. I make elements for each enemy and init it with that enemy entry. I then perhaps change how it looks based on if its recorded as being unlocked in the player data.
how
I can sub to some click event on my enemy element to react to its click and cus I know what enemy its showing, I can use this
You write it...
Turns out the issue was capital letters, I didn't know capital letters affected anything (Because I've never opened Unity or written code in my life until yesterday) and just had to change some stuff from capital letters back to lowercase and vice versa.
no but i mean, how you get all entries, and how you unlock it, is im just getting slighty confused. Sorry
public void Init(Config config, PlayerData player)
{
foreach (var enemy in config.enemies)
{
var enemyElement = Instantiate(enemyElementPrefab, enemyElementParent);
enemyElement.Init(enemy, player);
enemyElement.OnClick += OnEnemyElementClicked;
}
}
huh
you have some place of storing all of this information like a configuration object or a list of enemy data objects
then you should change it
That wasnt to issue shown in this photo but if it works it works #๐ปโcode-beginner message
i know, the thing is, i do it, cuz i dont fully know how to handle the other ways
also i can do a lot of bools
If you have any additional information associated with an "enemy" then you should ideally have a way to store this right?
e.g. health, sprite
Scriptable objects are GREAT for this
is just in the enemy
Then move it to a scriptable object that the enemies reference instead
huh?
Scriptable object cant be used as components can they? (Asking cause ive never used them, i just used base classes)
what even are scriptable objects, sorry
It was, for example "movementx and movementy" should have been typed as: "movementX and movementY"
you mean like a singleton?
I'm surprised nobody helping noticed that
You can just reference it on your component ๐
a file that you call using "instance"
i mean, i have an static object that stores the player's health, for the next scenes
anyway, back to my tutorial
Its important to seperate static data like this to make our lives easier when looking at this information in other places like UI
is that what you meant?
i do not know what you are trying to refer to as a file here but it's not accurate
No no it wasn't the problem on line 24 was the vector3 you didn't have a space between the Vector3 and movement and we did notice we just didn't give you the answer cause your IDE should if it worked.
Edit: though what you changed was a second problem with the code that if your IDE was configured would've also pointed out which is why they were try to help you with it.
statics are not objects, that is the point of them
i mean, the script is on an object btw, that just exists forever, this is how the player calls it in update for the health
soul = ValeriaMemories.Instance.memorySoul;```
i am gonna keep nitpicking your wording, please don't be offended
scripts are not on objects
instances of scripts are on objects
a static reference to an object != a static object
A random thougth just came to my mind, like... why does Unity save the enums you set on the editor as the Index of the enum and not the "id" of it, which is like basically the whole point of enums?
He did he didn't point it out cause he didn't want to spoon feed you, holy.
but i have it on the scene, like an object
For niche reasons it's niche for it to be "dumbed down" as an int anyway
Enums are beautiful
@acoustic belfry we want to seperate out the data like this so your UI can also reference all "enemy data"
public class EnemyData : ScriptableObject
{
public int health;
public Sprite sprite;
}
public class Enemy : MonoBehaviour
{
[SerializedField]
EnemyData enemyData;
}
im getting pretty lost.....
Spoon feed?
static objects do not exist
a singleton is a static reference to an object
o h
so in theory, this object exist forever thanks to a singleton.....
this is slighty more complex than i thought
again this is more of a nitpick but wording is pretty important in troubleshooting
I earlier said "static data" as we expect configuration data about enemies to mostly remain consistent at runtime
but why would you need that data btw?
no offense
cuz im the one confused and dumb
If i want to show all enemies in some user interface I can look at my list of EnemyData and do it dynamically
if your trying your not dumb
Are you comparing someone to a baby or something for being a complete beginner that knows nothing about Unity?
thx โจ
Spoon feed wtf is that
Yeah, but like, I hate that if I add a new item to the enum, it has to be at the end of it, cause else the whole project get messed up with stuff that had a value for it assigned in the inspector, it's kinda unnecesarely shitty tbh
i have all info i wanna show on my UI manager
MoonManager (name's related to lore)
i feel like this should be self explanatory
The trick is to not use as many enums ๐
i think it means to give you the thing in a golden plate
i mean
give you all stuff easily
no it means to not just give out answers but let the person asking to learn their mistake and fix it themself guided by others
yea but you seem to be unable to work out how to simply show unlocked enemies in this so you have clearly designed it badly
you came here to ask for help. I have worked on many games with external data configuration and there is a reason why its done this way...
just saying what i think it means
god damn please guys stop
so i have to put all information on my Static Script?
lets call it Memories
Hey what can I do about this?
scripts cannot be static
I think i have given you all the help I can. With good design we can make UI reactive to game configuration and game state without too much effort.
i mean
instance or object is the term you wanna use there
the script that the singleton has
the script is just the file with the code in it
Sorry for being the only one actually wanting to help you ๐
its ok xdn't
im trying to help a different thing ๐
i mean, the UI in theory works, everything works, is just the unlockable part that sucks
Yea as I said, you probably designed it in a bad way that makes this simple task (change some visibility or style to reflect some unlock state) hard
you tell me because I cant see what you have done soo far
{
if (cassielIndexType == 0)
{
if (cassielIndex == 0)
{
cassielJournalName.text = "Bitรกcora de Cassiel";
cassielJournalDesc.text = "El acceso a la informacion almacenada en la Base de Datos de Cassiel. Aqui puedes leer informacion sobre las leyendas que encuentras, la historia de gente que conoces, o como derrotar a los enemigos y sus significados";
}
}
else if (cassielIndexType == 1)
{
if (cassielIndex == 0)
{
cassielJournalName.text = "Prismas";
cassielJournalDesc.text = "Infodumping";
}
}
else if (cassielIndexType == 2)
{
if (cassielIndex == 0)
{
cassielJournalName.text = "Valeria";
cassielJournalDesc.text = "Infodumping sobre los personajes";
}
}
else if (cassielIndexType == 3)
{
if (cassielIndex == 0)
{
cassielJournalName.text = "Mortem Trooper";
cassielJournalDesc.text = "saracatunga";
}
}
}
public void setCassielStyle(int cassielJournalStyle)
{
cassielIndexType = cassielJournalStyle;
}
public void setCassielIndex( int index)
{
cassielIndex = index;
}
piratesoftware
yea that looks terrible, hard coded data using ints?
wat
;-;
anybody knows what can I do about this?
sorry
hey lists and dicts exist btw
dicts?
not a code question
what is it then?
@acoustic belfry
You can have a scriptable object type that is used to define the name and description for all these "cassiel" things and dynamically show this data:
#๐ปโcode-beginner message
https://unity.com/how-to/architect-game-code-scriptable-objects โฌ
๏ธ
Dictionary you can keep data in key, value pairs so they are easily referenced
oh!
how do you do this
no clue, manufacturer just gave up half way through designing it i guess
no I mean how do you make that formatting text mate
๐
-#
but what would list do in the operation?
but how do i make an scriptable object, in here says how i can use it, but not how to make one
You make your new scriptable object class type. You then give it the [CreateAssetMenu] attribute. This lets you make a new asset of your scriptable object in your project. Then you can edit the asset to give it the data you want (e.g name, description text)
Scriptable objects are a custom asset essentially that hold data and references to other assets
They are like materials where they are assets in your project except you decide what goes in them
the reference part is the one i get trouble
I presume you are having trouble thinking how to "reference all of these assets"
You can have a serialize list on your UI script and assign them all there
E.g a list of weapon scriptable objects
THEN we have access to all of our data
what exactly ScriptableObjects do?
you mean i just reference it drag and drop like other all objects i have?
Like materials ๐
Yea because you create assets of the scriptable object in your project
Using the right click create assets menu
Like when you create a new material we instead create a new "cassiel" instance
No idea what that is
is the only way i know, i dont know other, and putting important lore stuff on the editor i feel it slighty volatile cuz what if something goes wrong with the proyect, meanwhile if all infodumping is on the script is safe
Its no safer in a script file
i dont know how materials work, and cassiel is the name of the codex
you should be using source control to back up your project
e.g git or unity version control
then your data will be safe
it would make the entire if tree unnecessary
h o w ?
richt click where
oooh on the scriptable part
yay data
is below monobehaviour
you need [CreateAssetMenu] for that menu option to exist
[CreateAssetMenu]
public class TestScriptableObject : ScriptableObject
{
public string name;
public string desc;
}
btw what diferences scriptableObject and Monobehaviour i know is big, but im gertting slighty confused
ok
scriptable objects are assets
mono behaviours are components
oooooooooooooooooooh
now go my child and fix your data problem with scriptable objects โจ
ok 
but i still got confused on the activate-deactivate buttons thingy, the scriptableObject will just for make my wiki code dont suck
but ok
you didnโt explain the one thingo about data in scriptableobjects
wat
they did, i guess
Data in them doesnโt reset when you exit play mode
ScriptableObjects are good for things that are not going to change throughout the game
wait what
data in them dont reset?
then for what do static objects EVEN EXIST?!!
i got confused
i mean
scriptableObject's data is eternal?
well no
t h e n
in a component, if you put a value in the inspector 2 to, then play the game, the code changes it to 9, you exit the game, the value is back to 2
but yeah, then yea staticObjects are still usefull tho... xd
๐

SOs are immutable in the game. Not during editing time. Playing in the editor is part of the "editing time".
wat
Yea they should be used to configure data in editor and just read at runtime
like the info of a wiki
Such as doing game configuration for things like weapons or spells or a wiki of data
it's a good example yeah
Hey can anyone pls recommend a good tutorial where I can learn Unity C#
btw just asking, what diferences exactly would do, i mean what improvements i will see, if i replace the journal's hardcoded data with the scriptableobject data?
cuz i mean, the code would just be similar just that for the text it would reference the scriptableObject
Your UI can be constructed at runtime, you can make an element for each scriptable object asset meaning it's much easier to maintain
Makes sense. Well, thanks
Because the data is in one place it can be referenced in many places
Do make sure you look into source control to correctly back up your project so you don't loose data
anyone know how i access these settings? they are greyed out for some reason#
not a code question. and the built in materials are readonly, you need to create a copy of it and modify that copy
You can't edit the default material. Create one and assign it to this object
Oh, sorry
whys this thicker than usual
press insert
But what if i dont need it in any places
thats okay, its a lot better than what you were doing before
the situation may arrise and then you will be glad
But also something that i feel slighty odd
Ok, the Information is on the ScriptableObject. How i can make the Journal on the UI manager use it?
It would be the same Int tree
Just that instead of hardcoded text, it would be
Desc.text = ScriptableJournal.Desc;
?
Make an element via Instantiate() for each journal and initialize it:
public void Init(ScriptableJournal journal)
{
Desc.text = journal.Desc;
//...
}
Presuming you have a layout group and or scroll area of similar looking elements
How can I check if StartClient() succeeds or not? Function is returning true even though there is no server to connect to
public void onConnectButtion() {
if(int.TryParse(portInput.text, out int port))
{
NetworkManager.Singleton.GetComponent<UnityTransport>().SetConnectionData(
ipInput.text, // The IP address is a string
(ushort) port // The port number is an unsigned short
);
}
else
{
Debug.Log($"Attempted conversion of {portInput.text} failed");
}
Debug.Log(NetworkManager.Singleton.StartClient());
gameObject.SetActive(false);
lobbyMenu.SetActive(true);
}
thats cause the bool returns if the NetworkManager itself was started in clientmode .
can't you just check IsConnectedClient ?
Ah I see. I've now found OnClientConnectedCallback which I think is what I need
I'm now looking for a callback which fired if it fails to connect
OnClientDisconnected does this, which is a bit strange as it was never connected in the first place but ig it works
I've figured it out now so no need
Hey, is there a way to freeze the rigidbody rotation for a bit without losing the angular velocity?
If I set velocity to 0, I lose the velocity, if I freeze the rotation I lose the velocity, and if I store the velocity in a variable and reapply it after unfreezing it's not accurate as it didn't update.
Is there a built in way to achieve this?
well freezing would make it not accurate to the simulation, yeah?
you want to make it stop for a sec before continuing with whatever angular velocity it had before?
sounds like you would just do that - store velocity, set it to 0 now, set it back to the original velocity later
No, close but no.
I want it to continue calculating the rotation while frozen so when it resumes it resumes w velocity it would have as if it never stopped to that point.
so like, stopping the graphics but not the actual simulation?
maybe, depends on how you see it
if I was rotating for 50 on the x axis and froze, I don't want to resume after 5 seconds at 50 velocity on x but instead what it would be if the simulation was running that entire time, so maybe 20
yes
what are you trying to achieve?
I am controlling a flying object that can flip(with user input), and I want to stop that flip while the user is moving the mouse to pan around, but resume when the user stops giving input.
Not sure if it will feel good or bad just wanna test it.
I initially didn't change the velocity at all and that felt weird when user was trying to pan against it, then tried fully stopping it which felt weird when you stopped moving the mouse as there was no rotation at all so I wanna give this a try, lmk if you have a better idea.
oh god a UX question, im horrible with these
yep, so am I, I just try stuff till something works
im usually better at identifying/guessing UX issues than fixing them, so.. may as well try
my first thought is that the immediate stop/start would be jarring - so maybe smooth the stop/restart?
(with this logic, except with smoothing)
yeah, that's a decent idea, lemme give it a try
Any ideas why this is always throwing an error? portInput is a TMP_Text component
Debug.Log(portInput.text);
if(int.TryParse(portInput.text.Trim(), out int port)) // Set the socket
{
NetworkManager.Singleton.GetComponent<UnityTransport>().SetConnectionData(ipInput.text, (ushort) port);
}
Debug output seems normal
what's the error
The converstion fails and returns false
that's not an error, but ok
have you tried checking portInput.text.Length to see if there are chars you aren't seeing
good idea. Will do that now though I did Trim()
there are some invisible non-whitespace chars too
i would hope they didn't get in there but im not ruling it out yet lol
yep ๐
eol? I would have thought that would be trimmed
And is there a better way of getting a number of from an input?
Ah this fuckin thing
The TMP_Text of an input, and specifically of an input, has an invisible non-printing character that isn't removed by Trim
Lemme check my post history for what the unicode of that was...
OnValueChanged on it then keep track of it in separate string
put the InputField mode to numerics only it has its own regex thing built in
.Replace("\u200B", "")
It tacks on a \u200B character at the end of the input field. If you're ever getting .text from it, you need to replace that with empty string
so I just used a TMP_InputField object instead of TMP_text and that works lol
why do you get text from a TMP_text in the first place lol
assuming you had inputfield in the first place ๐ค
I was doing it like this
wait, ZWSP is whitespace though apparently it isn't.
In my case it's because I'm generically getting info from a UI panel containing both fixed values and user-entered ones, so I just get all the TMP_Texts in the panel and go through them
For whatever reason, .Trim() doesn't remove it
so has a serializedField for TMP_Text instead of TMP_InputField and passed the text component in directly instead of the input field. I thought that would be more direct and therefor easier
ohh I would assume one would have the values to the textfield , before displaying it to UI
In my case it's two different processes, one that reads in data and puts it up on the UI, and another one that exports it, and since some of the data is user-editable I thought I could just shortcut the process by letting TMP_Texts be the Source of Truth and reading them at export time
yeah that worked flawlessly, it feels truly good to use now, thanks!
interesting.. first time I've heard, I'm sure you got specific needs for it.. for me feels icky in a sense , kinda goes away from an MVP type pattern I'm used to
first try ๐
using playmaker
Addressables.LoadAssetsAsync<GameSettingsSo>(BASE_SETTINGS_KEY).Completed += handle =>
{
if (handle.Status is AsyncOperationStatus.Succeeded)
{
DeclaredSettings = handle
.Result
.OrderBy(settings => settings.LocalisedTitle.GetLocalizedString().Length)
.ToArray();
InstantiateIfEmpty();
}
#if UNITY_EDITOR
else
{
Debug.LogError("Could not load base settings");
}
#endif
};
How am I supposed to do this if Unity doesn't allow that? :( Exception: Reentering the Update method is not allowed. This can happen when calling WaitForCompletion on an operation while inside of a callback.
What am I doing wrong here?
I am using playmaker, and I have a polygon collider2d on the object.
However, its as if the game doesnt even detect the mouse. Am I missing something?
purely guessing, but - it may be using old OnMouseOver events, which wouldn't work with the new input system, which is set by default as of v6.1
OnMouseOver uses raycast for colliders no ?
i thought the OnMouseX messages just didn't work with new input system?
i haven't tested, but that's what ive been seeing other people say
hmm let me test that rq
i had that yesterday, i think Chris is right, it only works with the old one
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/KnownLimitations.html
MonoBehaviour mouse methods (OnMouseEnter, OnMouseDrag, etc) will not be called by the Input System.
shit.. you would think they now put that on the OnMouse docs ๐
they really should for unity 6.1+ since the input system is the default there
"we gonna switch you to new input system but tell you nothing about old methods not working in docs for OnMouse"
would be something i would expect too
guess now its a good time to click this
You could use both input systems
yes, its just a weird oversight for unity not to mention this change in the new 6.x docs for OnMouse
you have to find it in the new input system docs which most newbies wont know about right away
Oh absolutely
hell even a nice in-editor message
"we detected you are using OnMouseOver with new input system , this will not work" or some shit
Trying to make regex for ipv4 input validaton. For some reason I can type this in the input field, but when I go on regex101 it does't accept. Any idea what the discrepencies are about?
it's definitely partially working as I can't type letters
because that doesn't fit your regex
you limit consequtive digits to 3 max
Right, which is what I want
oh i misunderstood your question
but for some reason I can type 4 consecutive digits in the input field
aight thx
pretty sure that's validating individual characters, not the entire string
ah, it does say 'character validation'
Is there a way to make it so a script file takes all floats written in it with only 2 decimal places? I don't wanna use Math.Round() for every multiplication between such variables
if its just for display use F2
I need them for calculation purposes, not presentation
It's generally better to just let the math happen with the real values and only round at the end
floats preserves full precision until you round or truncate it
Yeah that is true, but some of them create veeery long float values, with .0000000001 thats throwing out my script
that shouldn't throw anything off unless you are doing something silly like comparing floats using the equality operators
Mathematically, that's basically identical to 0, how is that throwing off the math?
Well, about that...
Do the math, then round the result
yeah so the issue isn't that you need to change the math, the issue is that you are doing comparisons wrong. use Mathf.Approximately to compare floats rather than the equality operator
Well, technically I'm using the more/less operators, not the equality one
then if somehow regular floating point imprecision (which will not be solved by simply rounding the floats) is throwing off that, then compare with an epsilon
which Mathf.Approximately is doing for equality
Basically, In one of my methods, I have if statements, where it compares the current position of an object and the outer bounds of a box it is in
did you know you can use the Bounds struct for that instead of manually checking
Not sure if I can use that for my current script
Can you tell me if this is optimized code, or else I have a memory leak?
i'd bet you could
Honestly, it's better to explain my problem with the context included
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ 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.
it almost always is because this ended up being an XY Problem
if you posted the code properly..also are you even sure what a memory leak is ?
not seeing anything drastic that would cause memory leaks..
Hello I am new in Unity So I know how to use Unity because of Blender but I don't know about coding So I watched Roll a boll Tutorial on Unity learn and only understood some basics like Start, Update, Vector3 and Variables so many things I didn't understand so can anyone tell me what should I do next? Should I watch the same tutorial again Or something else?
you should watch the tutorials a couple of times , its not going to make sense right away
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ 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.
check the stacktrace and see where they are coming from, otherwise you need to use the memory profiler or something like that to check
you're meant to read it not spam the command again..
links for large code
this is not likely the code you shown
Ok I will try
A tool for sharing your source code with the world!
also have you looked at these other one https://learn.unity.com/pathway/junior-programmer
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
this is explains a lot more than Roll a Ball iirc
not seeing anything here that would even touch the Jobs systems or create a memleak
after clearing log window do they show up ? did you try actually removing the script and see if the warning come back after clearing ? etc.
debug starts with simple steps to isolate where issue comes from
Ohh yeah I thought there is only one coding tutorial thanks for the link roll a ball tutorial was kinda robot
yeah these are more detailed , you will probably have better luck.. Also yeah it usually takes a few passes to let it "click" its a lot of stuff but with patience and time you will start getting the hang of it
doesn't hurt to also do some focused on c# specific tutorials, unity ones is trying to teach you both the API and C# at same time it might be overwhelming for some
things like "what are functions, how do we write the syntax" etc. I havent seen the entire learn course but not sure if it covers those
Specific tutorial where? On YouTube?
ehh youtube is a gamble. You can find the resources straight from the creators of the language https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
there's plenty there too
I'd recomend you start with simple apps like a small calculator, atm system, or like grades for students etc.
specifically these are great because its
handle user input
do logic with values from input
visualise logic output
which is all games end up being if you reduce them enough ๐
These things will be same in Unity? Like same functions?
Unity might/will have varying prefered ways of doing things but you can use everything there in unity
everything you learn there will be transferrable to unity
except for specific Console app quirks like Console.WriteLine etc.
Unity have their own function for that like Debug.Log
but the concepts and variables will be the same
I know how to use Debug.log so no problem
good , thats like the best first line to learn in unity
make it a priorty to print everything you're doing so you can see your results
Console app is just quicker because you work directly in the "Log window" without worrying UI or cameras etc. Balance it out
now you got online compilers anyway so you can easily do it all in browser like the learn courses on .net
When I turn off each script, I think I found a creak that causes me to get a leak https://paste.mod.gg/hranmwvnfmzt/0
A tool for sharing your source code with the world!
is there a better way to do nullchecks than the wholeass if statement every time? seems really inefficient
but also I'm dumb
no idea why it would unelss you got some weird recursion going on or something, how are you certain ?
Depends on the check
wdym a "whole ass if statement" lol
whats wrong with if statements
You'd have to provide an example or two
Hmm I am using Vs code
they are literally the base conditional for the language and most logic.. lol
if it's a UnityEngine.Object (components, GOs, etc) then you can just use the boolean conversion if you want a shorter version that does the same thing
Yeah I do
that's so fucking wise
no it's just... a shortcut
VSCode can also do Console apps, the window is just nested in the app instead of a sepearate window like VS
Ohh
just make sure you have the proper plugins. if you install Unity plugin it will install the rest
Yes I have
for unity objects, you need to explicitly use an if statement if you want to do logic based on if an object is null.
that is with if(myObj == null) or if(myObj) though i tend to write out the full version for consistency
For regular classes (stuff that doesnt derive from monobehaviour or unityobject) you can use operators like null conditional or null coalescing ? and ??
makes sense, thanks homie
good , you should see it there then
yoooo nav we talked yesterday about the whole database thing
ive decided to go with .net and use apis and make web requests for data. currently its just local but if it were to go live id get a server or something
do you have any objections? or think this is a good idea
yes this is basically what i originally suggested, its better to make a seperate server app to interact with the DB directly and only make RESTful calls
Your Unity app should never have Credentials to anything , especially a database connection string etc.
anything on client can be decompiled and stolen
ah i see gotcha. yea so the way this is setup is that its a different project.
so yeah a nice WebAPI with .net core is the way to go
do you still think hard coding passwords in there is unsafe?
not as risky if its just living on the server but should never store in code itself but inside environment variables / key systems
ah ok so something like azure
Ill probably just go with azure for safety eventually
azure has keyvault or something like that yea , also if you use a VPS to host the api that can also just store it in the OS with ENV vars
np. goodluck ๐ซก
What do I need to learn to build a basic online game (using a client server model)? Iโve done a few unity projects, but my university coursework and internship so far dont have anything to do with networking so Iโm lost
Is there a good resource or book thatโs relatively up to date I can read/work through?
Thank you
Hey, guys! I have a "serious" issue with a null reference, like everything was fine I didn't have wrong syntax or whatever when getting the component of the game objects and basically everything was fine, but at the end I found that the problem was in timing and what I mean is that the scene needed like 1 second or so to load the game objects and I had to create a coroutine for this purpose because I am currently on my project using data persistence approach because I want a game object to persist between two scenes and really the problem I have sometimes it that I cannot find what is causing the null references sometimes when they aren't obvious. What do you think how I am supposed to deal with them maybe some professional advice?
check the stack trace
Yes of course but sometimes it isn't really obvious I mean it isn't especially when code is getting larger and larger
Maybe I have to use if statements
to check null
hows it not obvious'? it tells you the exact line that caused NRE
sure but that can be a band-aid sometimes to a much bigger problem
on the NRE message? which line does it say and which script
there is no doubt except if you have multiple reference types on that line
not sure I get your question then
if im understanding the issue it sounds to me like youl have to set up a Single Entry point script
I always view console for these purposes
little confused then on hows it not obvious which one is throwing
and I dont ignore errors like this
the WHY is for you to find out, NRE will only tell you WHERE
Code can't show you "why" anything
the why is just, either it was set to null, or it was never set to anything else
The why is always the same - because that variable is null
Now, it was first time I was dealing with null reference that wasn't really obvious to me like I had to call a coroutine because like I said I am doing data persistence and the objects weren't loaded at the scene load immediately and I had to create a coroutine to wait for one second for example
Because I was trying to get the component of a game object and it wasn't yet instantiated at the scene load and thats why it was null
yes order of events is a common issue especially with poor design
single entry point
thats why you typically would use Event
an event will tell something else when its "ready"
instead of you timing it poorly / guesstimating
haha race conditions go brrrr
I was using Observer Pattern for this purpose what do you mean
yes observer pattern are events, so why not fire event when its ready and assigned instead of a random coroutine with a timer
yeah youre on the right track with the observer pattern it just has to wait not some arbitrary amount of time
but rather until the scene is ready
guaranteed ready to be exact
the objects weren't loaded at the scene load immediately
yet you were trying to access them then.
you might have it in your project, but you aren't utilizing them here
it would help also if you showed us which line and some context for it
there are other events that you can use but without further details its hard to make a specific recommendation
in general you should try to design to not have race conditions as well
Yes you are right I was trying to use observer pattern but it wasn't complete, I think I have to create an event and just do what you said
yes even that can have a flaw depending when you subscribe to the event . Eg is the event firing before other scripts that care for it subscribing after, and so on
Yes bro its all about good design without proper design its hard and when code is getting larger it will be harder and harder to track issues
And I think that's the most important part of programming like really structuring your code that way, so it will be maintainable, readable, efficient and well structured for you if working solo or on a team where things are getting more confused.
Its easy to write code but ๐ this is the hardest part
that's why software engineering is engineering
comes with lots of trail n error IMO . Sure you can copy patterns online but it wont be exactly specific to your project, thats best done for you to try what works and what doesnt and eventually make your own bones
its the most important but also the hardest part
in my opinion
!code ๐
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ 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.
alr
basically my rigid body isnt falling after i made some coroutine code
lemme paste the code
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
heres some other code which is sort of linked to the co routine but probably isnt the issue
but when i click play i cant move my rigid body or anything
dont see anything in these two scripts that touch the rigidbody movement ?
missing context
what other info would u wanna know cuz tbh im not sure what else to tell u
ok now its falling wth
๐ญ
magic solution ๐
Magic where :?
it was prolly broken in general maybe cuz my roll timer and roll threshold values were 0 in the inspector
where is the code that actually moves the rigidbody ? are there errors in console ? etc.
all good now for sum reason dw
im sorry but what you mean via Instatiate, or well, instatiate
QwQ
Surely you have called Instantiate at some point by now

i dont recall it
sorry for dissapoint.....
Have you used prefabs in your project at all
pretty sure they have spawned things before lol
Its such an important function you really should know it
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
there are 15 separate results in their history of them demonstrating the use of Instantiate
yep
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
you meant this!
GameObject nuevoProyectil = Instantiate(balas, balasPos.position, Quaternion.identity);
no i mean, i forgot it was called instatiate
i dont see this code very oftern cuz is inside a method i always use
long day im sure ๐
so i remember the method and not the word instatiate, i just call it, spawn
hopefully it makes more sense now
next time just google "unity instantiate" and you will remember
Hey I'm making a top-down game and for some reason my projectile only bounces off of walls when the wall is not locked in place but when I set restrict the x,y values of the wall the projectile collides with the wall and just stays there
show relevant !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ 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.
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 currentVelocity = rb1.linearVelocity; //Get the current velocity right at the moment of collision
Vector2 reflectedVelocity = Vector2.Reflect(currentVelocity.normalized, collision.contacts[0].normal);
speed = currentVelocity.magnitude;
rb1.linearVelocity = reflectedVelocity * speed;
rb1.position += reflectedVelocity * 0.01f;
}
this is projectile collision code
I don't know if there is any other relevant code but the walls have a tilemapcollider2d and rigidbody2d
hint: log relevant info such as the velocity used
hello everyone Ive been struggling with an issue for so much time now, Im making a pong game clone, and the provided code is the ball script and a ball spawner script attached to a ball spawner game object, the issue is as soon as the ball spawns the ball stays still and doesn't move at all, ive tried logging the velocity it still prints a non zero velocity in the console so I have no idea what the issue might be, here's the relevant code:
omg this is so annoying I cant send it
it's too long
!code ๐ Large Code Blocks
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ 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.
heres the ball controller script
https://paste.mod.gg/rzbmmrbktzbl/0
A tool for sharing your source code with the world!
good game btw from your pfp
heres the ball spawner script
https://paste.mod.gg/nkygczkdsfgv/0
A tool for sharing your source code with the world!
show also the inspector
ideally the entire inspector window when you have the ball object selected
wdym
which part was unclear?
you mean in unity?
yes . . .
ideally the entire inspector window
simulated is unchecked

the thing is, the buttons are shared. I mean, thats what made all of this mess
how does it look?
I just imagined there was some large list/grid that is shown which should be easy to fill with elements automatically
Does a dictionary allow for duplicates by default? Like two different keys pointing at the same instance as a value?
keys are unique values are not
alright now im running into another issue
but not hard to make a wrapper and make unique value dict
just a comparison
Actually no, it would require iterations
So if I make like a dictionary that basically is a reference to the id of a gear prefab and its prefab, the id string should be the key or the value?
Doesn't really matter much right?
are just 5 buttons, shared, by all information
thats why the tree
Ah, you'd have a Hashset for the values to make a truely unique key/value
it ain't pulished by sprites for now, so except it to look ugly
three tabs for the categories
5 buttons that change depending on the category
a display of Info
of a photo
and of a name
Is there a reason why these "Button" buttons are shared?
Do you press one to view information about the thing?
A hashset huh? Can you expand on how that would work?
if not, i would need to make an army of buttons
i mean
in theory would be
5 x 3 = 15 buttons
Don't worry about it. What are you doing? Serializing/Deserializing? ID key -> Prefab value table
Somehow i'm facing a situation where lighting does not work out of the box. I wonder why. Anyone come across this before?
(the cube/plane is not affected by the directional light)
yes
You can just spawn buttons dynamically based on your wiki scriptable objects
layout group
wat
Basically I want to have the gear set to an id that can be easily look for when having to save and load, so I can give each player the gear they had
oh dear no wonder this didnt make sense to you
ugui has horizontal and vertical layout groups to auto layout children for you
So should I use a hashset for that or a dictionary is ok?
a dictionary is good here
and how do i add tabs to it
If all those "tab" buttons do is change what is in the button list, you can just rebuild it when you "change tab"
The idea I have is to basically make the gear, when checking if it's valid in inspector, automatically send a call to the dictionary, for it to generate the id key as the name of the item, check if it's on the dictionary already and if it's not add it and look for the prefab on the folder with the same name as the value
The attached picture shows the inspector for both scanners right and left (ball inspector is above in the chat), the issue im running trough is that when the ball goes trough that edge collider it doesnt detect the collision therefore the log inside the if statement doesnt get printed heres the relevent code, the ballcontroller script and the ballscannerScript
https://paste.mod.gg/wnzxyfxlnijx/0
https://paste.mod.gg/dlajkzkbydvl/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
Is this a decent way of doing it?
rebuild? how i do it?
if you're going to ID by name you can just use strings but the proper way here is to generate a GUID for each asset instead
fixed, i had to mess around with my urp pipeline asset
A what? How?
So is it editor or is this deserlization save/load in game
sounds editor so you can use Asset IDs too
this has been the major issue which had demotivated me to come back to this project
tbh
The gear is meant to be added to the dictionary on the editor, when making setting the parameters and all, yeah
Yeah, I was thinking of this too, like each component already has an id assigned by unity anyways right?
But I don't really know how to access it
So what exactly is this ID and what is it for again? Is there a reason you can't just use references as the IDs if this is editor
Not really, no, it's basically meant to be unique and faster than looking by string on the prefab folder
should be fine to just use this
https://docs.unity3d.com/ScriptReference/AssetDatabase.AssetPathToGUID.html
assign this as your key string ID, assign the prefab as the value
https://docs.unity3d.com/ScriptReference/AssetDatabase.html
That's what you usually use for asset lookups and stuff if you're making some editor tools
update what the buttons say and do each time you change "category"
you could destroy them all and re make them or re use the existing ones (hiding extra ones and spawning extras if needed)
This is what I do for UI like this that can be refreshed with changing data
Mmmmm, ok, so this basically would give me directly the path to that folder in the editor, but I wouldn't be much reliable to look for that on runtime right?
You need to hardcode the ID into the asset if it's at runtime
what people do is usually have some OnValidate method and grab the asset ID and make a property inside of the asset for it
Or just use c# GUID library and generate your own
why am i getting this when i try drag the rolling script onto the object
You cut off the screenshot of the editor there. Show below asset directory there
Make sure there are no compile errors and that that file name and class name match
yeah there were none
Show your console
works now
all good
oh
now im back to where i was before
very cool
how do i select one prefab to load from resource?
like with text its resource.load(Levels/level2.txt)?
AssetDataBase.AssetPathToGUID() would return null if the path doesn't exist right?
Creating a train game where you are placing down the rails. Would anyone be able to point me toward some guidance on how I could do the pathing on that? It is based on a grid and the track could loop back around and/or split (with player controlling direction).
probably could use splines feeding the grid coords as positions along the spline
have the train follow that.. the rest just sounds like normal tile placement (having bends, splits, str8 pieces and whatnot)
yeah if it's a grid then I expect you to just have a bunch of railroad assets instead of generating it via spline
not that you still cant use the spline tool, but you'd use it to figure out the indices to build for what indices it goes through
Alright, took a brief look at splines, I am not totally sure how I would go about feeding the coordinates in the correct order. The order the train follows and the order of placement won't necessarily be the same so how would I go about knowing what order to feed them in?
Also I do plan to use grid based assets for the visual part. Splines does seem good for smoothing the movement with corners.
This is 2D top down btw
Another idea is using a texture too assuming there is no y
1 pixel = 1 index
but would need gaps between so you'd probably have some flowfield instead
thanks :3
If each button gets initialized in some way you just do it again when stuff changes
but, how do i storage what tabs should spawn
Maybe each tab has a script that has a serialized list of the scriptable objects it shows?
many ways to do it
simplier?
that is simple
no i mean, you said there was many ways to do it
Oh, well another way could be each tab has an enum to specify its category and thats used to retrieve the list somehow
but may be a bit harder for you
switch(tabCategory)
{
case TabCategory.Shoes:
return shoeList;
}
this seems easier but what this have to do with the button-spawning/despawning
this just makes the tree more organized
you need to see the bigger picture of how this UI could work
wich is good, but not what im having issues with rn
we want it to show a list of information and you can change categories from a smaller list of buttons
therefore we need the category buttons to update whats shown when clicked
meaning we need our data to be sorted by these categories and we need to know what to show when the category button is pressed
yeah
like the tree
just more organized
i just didnt used this cuz.... i dont know why honestly, but yeah
state stuff
e.g.:
public enum Category {Shoes, Cats}
public class CategoryButton : MonoBehaviour
{
public UnityEvent<Category> OnClick;
[SerializeField]
Button button;
[SerializeField]
Category category;
private void Awake()
{
button.onClick.AddListener(() => OnClick.Invoke(category));
}
}
often helps if we make a mono that performs the button task and holds extra information
i dont follow ;-;
it may seem daunting and complex. I would write a large example but i dont have the energy or will rn
ok
im getting a logic error with my rolling coroutine which is supposed to negate fall damage if anyone wants to look at the code below, first link is the fall damage script, second link is the rolling coroutine script
https://paste.mod.gg/cidcphdzgawn/0
https://paste.mod.gg/fchpxgiywwaw/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
i still take fall damage despite what the console says and the fall velocity is defo not 0 when i hit the ground so i suspect its smth to do with execution order
If the log says FallVelocity is 0 then it's 0
If the player is taking damage, try logging anywhere you change the player HP
Find out which one it's happening at
i sort of phrased what i meant wrong mb, as in if theyre gonna take fall damage then it should print the value the fall velocity was before setting it to 0
if that makes sense
It will print the value of FallVelocity as it is at the time that log runs
this may help you a little by demonstrating a reactive UI but using pre spawned elements
https://learn.unity.com/tutorial/grouping-and-layout-techniques-for-ui-components-2019-3
perhaps you can do the same, have a category field on your "wiki scriptable objects" and the category buttons show/hide things depending on what category is selected
oooh nice
I have started to try things in a different project but i cant get my player controller to work, i keep getting this error code : You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings
Unity input package has been uninstalled for a while and yet its still telling me i switched to it. Can anyone help?
Literally just plug that exact text into google and get a step by step guide to how to change the input mode
any help would be useful
You need to set your active input handling mode to the old system
thanks :3
omg making a state machine for a navAgent is SO much easier than for the player
not having to deal with all the input logic and just have it follow commands in each state
i finally understand it now haha
I use Cinemachine set to Follow. I move my player in FixedUpdate with transform.Translate(). Once the camera "caught up" with the player it starts to jitter. If I move my player in LateUpdate() or I cap the framerate to 60 or 120 it is fixed, but I'd prefer not to do either of those.
Is there a third option?
Hi! I've taken a class on C++, but I've never used Unity. I want to import a function to a script to be used by another script, and usually you would do #ifndef, but I don't think that works in Unity.
I made an empty object, put both scripts in the object, and get the error message of: "NullReferenceException: Object reference not set to an instance of an object
DateDisplay.Update () (at Assets/GAME/UI/Scripts/DateDisplay.cs:37)"
Either move your player in regular update, or let physics move it(via rb) and enable interpolation on rb, or implement something similar to rb interpolation in your own logic.
Setting the cinema chine brain to update in fixed update might also be an option, but it might not eliminate the jitter entirely.
P.s. Honestly using transform translate in fixed update sounds like a terrible choice to me. I can't think of any reason to do that.
Unity uses C#, not C++
Oh
Start from configuring your !ide to get ingellisense and error underlines.
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
โข :question: Other/None
Then I suggest going on some C# basics.
Im telling you to configure it/your environment to work with unity correctly.
The bot message covers that.
Ah
When you're done, it would help if you share your !code properly too.
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ 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.
https://paste.mod.gg/ivvigzqcwpez/1
I connected the visual editor and it doesn't see any errors
A tool for sharing your source code with the world!
Take a screenshot of your VS window with any script open, like before so that I can see that it's configured properly.
Still not configured. Follow the installed manually guide and don't skip any steps.
As long as you see Miscelenious files here, it's not configured
Wow. So all I had to do was capitalize the function name ๐ญ
Thank you so much for the fast response tho because the new editor did let me know that
And it works now
So, the GearDataBase should be a scripteable object here?
Cause I kinda wanted to make it a static clase, but I clearly cannot, sicne I need to modify their values lol
Could like make the SO kinda like an singleton to access it wherever??
