#💻┃code-beginner
1 messages · Page 694 of 1
are you running set on the clone..
no, i shouldn't need to
Maybe show the full !code of the Projectile
i've tried many ways and this was the least bad
Oh, bot isn't working
Will Unity instansiate copy non-serialized values at runtime?
eg. if layer is private and not marked with SerializeField i wonder if that wont copy
Put the code in
https://paste.mod.gg/
and send it
A tool for sharing your source code with the world!
this will make any experienced programmer cry, so be careful
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
would do you some good to have comments certainly
In this script you're calling Set after cloning it.
Also... if this script is Projectile, why are you calling GetComponent<Projectile>()
just use this
also, with c#, you dont need dedicated getters and setters, that can be done when you define a variable
oh yeah i forgot. when i call set it spawns more of them for some fucking reason
inline and is a lot prettier
And instead of GameObject clone = Instantiate(gameObject), just do Projectile clone = Instantiate(this)
i thought about doing that but was worried it might then miss data from other scripts
It won't
which i guess is ironic considering that it seemingly made me miss out on data from the projectile script
It'll copy over any serialized data from all components on the object and just return the type you gave it
well that didn't quite fix it
Are you calling Set after you clone it?
If not, it's never getting set
not anymore, no
it should carry over the data from the original, right?
Then that'd be why
Only if it's serialized
How is it supposed to copy over a value that it literally cannot read or write to another object?
idk im fuckin stupid
You should probably make these variables all [SerializeField]s instead of having all these setter functions
you can cut about 50 lines of bloat just by using inline getters and setters
And another 50 by storing GetComponents in Awake instead of re-getting them
If you have a public GetLayers and a public SetLayers you should just make layers public
true, its also just bad practice to continually retrive components instead of storing in memory
or use a public property
why was i perpetually told to never use public variables
you can define variables like this:
public LayerMask layers {get; private set;} if you wanted it private
You basically already are
you're just doing it with extra steps
Whattt i always use public and always set an instance so i can use it
using public is fine; if youre doing it for the right reason
is that bad?
if you're gonna make the data publically accessible for reading and writing you might as well just make it public
since youre accessing that data outside of the class, public is perfectly fine
What if other code sets those public values to weird values and breaks the game?
or use a property:
public LayerMask layers {get; set;}
that would be horrendus design or injection
what should i do? i use public so i can set it in the inspector usually
[SerializeField] private
whatever else
Serialize?
]oops
[field: SerializeField] public MyType MyPropertyName {get; private set; }
allows you to serialize a value while having it publically readable, but privately writable
ooh
serializefield just makes it visible in the inspector
In this specific case, the setter would also need to be public because they're modifying it from outside anyway
so im gonna make most of my stuff private lol
what if i want to access that value in a different script?
cool thing about properties is you can also write more bits of inline code instead of just (accessability) get;
Is there a way to like simplify this like with a method call or something? Like, get me every item on each of the sublists
you can do get { bla bla bla return x; }
are public variables automatically serialized
Yes, which is why you need to specify them to be serialized if they're private but you want to edit them in the inspector anyway
Yeah Linq has Select and SelectMany
foreach (InventoryItem item in allGear.SelectMany())
if its private how can i access it in a different script? i usually make it public and set an instance for the script
You don't
is there a better way other than making it public
That's what private means
i see
So this does that over all lists right?
The code does exactly what you tell it to do. Nothing more, nothing less.
so public if i want to access it in a different location
private if i want it to stay inside that class
np
not you bozo lmao 💀
😹
ikyk
yeah, sorry forgot you also need a thingo in there, eg.
private void Test()
{
List<List<string>> listList = new List<List<string>>();
foreach (string listValue in listList.SelectMany(l => l))
{
}
}
l => l? Is that a reference to itself?
so many list
l here is a reference to the lists inside listList
It's a function that returns its input. SelectMany takes a function that is meant to return the objects you want from the list. Normally, you'd give it a condition, like "Anything where this variable is true". But in this case, you just want everything. It'll give you an enumerator over every item in the nested lists
So lets say I would want it to give me just the items that have item.gearType == GearType.Weapon. Can I do that?
You can chuck in a Where()
foreach (string listValue in listList.SelectMany(l => l.Where(s => s == "Thingo")))
{
}
(and l and s here are local variables, they can be named whatever you want)
Yeah, I don't get the arrows pointing at nothing at all lol
Yeah forsure, I found them very confusing at first too, it's basically a contextual micro function
Yeah, I read these I just end up more confused
Like I read this and get like no info at all out of it
Actually in this case.. it's a lambda
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
It's a lambda expression. A way to make a function in a single line. For example, l => l is identical to:
private object FunctionWithNoName(object l)
{
return l;
}
I know memes are not the vibe here but it really is just
Basically the => is doing like.... this member returns this expression?
It is separating inputs from outputs
The stuff to the left of the => are the inputs. The stuff to the right are the outputs.
I just don't get why would u need an input, specially if the output is exactly the same as the input
Because SelectMany takes a function as a parameter
int GetInt(int i)//Regular ol function
{
return i;
}``````cs
int GetInt(int i) => i;//Expression bodied``````cs
(i) => i;//Lambda where for every parameter i, return i```
So this basically passing a null function?
Like does nothing
identity function
a null function would be one that returns null
Use case: (return only values less than 5)cs int[] values = {0, 2, 6, 3, 10};Using Where( i => i < 5) would return the values {0, 2, 3} as an Enumerable that would be iterated by the foreach.
So this is doing.... for each parameter, return the same parameter if... the returned parameter of parameter equals "Thingo" is true????
It is going through the listList and returning every element for which that thing's s is equal to "Thingo"
And putting them in the resulting collection
Then, you loop over that collection
But why is Where also asking for a function? Like, doesn't it need a condition? Shouldn't it just be a bolean and be s == "Stuff"??
s == "Stuff" is a boolean. Not a function. It would be evaluated to true or false right there and passed to the Where function.
Instead, it calls the function on every element in the collection, and if the result is true, it puts it in the list
The docs on Where
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-9.0
The two overloads are with parameters of type T and the predicate returning a bool (the second also taking into account an index etc)
So, I need to basically pass it a function that returns a bool, right?
Yes, it specifically takes a function that returns bool as a parameter
It doesn't need to be a lambda, you can use a real function as well
So, this is a valid thing I can do? Is this right?

It compiles. Should probably do what you expect but I don't know what's in any of those lists
Was that the purpose of you wanting to iterate the collection of collections?
#💻┃code-beginner message
To check if some gearToShow collection (dictionary perhaps) Contains the item?
I want to hide all the items that do not appear on the HasSet "gearToShow"
From each of the items on each of list of "allGear"
Hmm, maybe you should just hide them when removing the item from the gearToShow collection instead of iterating like this on the side?
Or if they are added to the gearToShow collection at some point, all gears inactive and set to active when added to the collection.
Hey guys! Where do I ask questions about lighting?
Mmmm, maybe you are right actually
I think I had a reason as to why not just hide it directly, but I can't think about it right now
One reason would be if the dictionary was initially populated already but that isn't quite possible if from the Unity inspector and if added immediately, you'd be able to populate and setup each active state on-the-go.
I think it was so I could iterate better for the items that are actually currently showing just in case
But since I changed that to a HashSet maybe it's not even that good of an idea anymore
Definitely not here (this is the beginner coding channel, not to be confused with a just beginners in general channel)
Try #💻┃unity-talk (they've archived #archived-lighting now so I'm not certain where you'd ask other than perhaps #💥┃post-processing or #1390346776804069396 - when in doubt try #💻┃unity-talk )
Thanks a lot! <3
holy balls GPUs are fast bro
2000 frames of 64x64 IR seeker simulation
then mip mapped to 1 dimensional audio signal
all within 2.3 ms
NVM
I have an editor bug in the collision matrix I cant resolve. I've tried restarting unity and the computer. Seen this one before? Know how to fix it?
why laughing?
did you try making the window wider?
https://discussions.unity.com/t/shifted-layer-collision-matrix/1546525
a bit different but maybe some of their tips help
also apparently fixed in later versions.. which one do you use?
Reproduction steps: 1. Open the attached “IN-83682 Physics Layer Collision Matrix Bug _ Repro FAV.zip“ project (link in the internal...
am making a 2d geometory dash type game will cinemachine be better for tracking or direct script
my first thing
that dosent show anything 💀
I maintain that every single unity game should be using Cinemachine
Also scripts and Cinemachine are not mutually exclusive
but my character is jittering is it cuz cinemachine or just movement
am using a slerp for movement too still
like its going back n forth bw pixels but moving
Jittering character is usually a sign that you're using a Rigidbody without interpolation
Or that your code is breaking the interpolation
If you do interpolation and your code doesn't break the interpolation
i didnt knew it was an important thing leme try
This part concerns me
What do you mean by this
for rotation
It's possible your code is directly modifying the Transform, if so it will break interpolation
am making player face mouse with slerp
its interpolate still jittering
do i remove slerp
If you're doing so via the Transform that's the problem
You cannot touch the Transform directly
transform.up for rotation and rigidobdy.linervelocity for movement
Yes that's wrong
Don't touch the Transform for a Rigidbody or it will break the interpolation
Working but without interpolation
You need to rotate via the Rigidbody
oh
No, everything needs to be via the Rigidbody
That's very tricky to use for mouse rotation
Because it can only go in FixedUpdate
Easier to directly modify the rotation property
ok leme try thx
i did with rb.rotation but now my player is not going forward at that angle
thx bro u saved me for hours or searching on the internet
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
public float speed = 50f;
private float targetAngle = 0f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.interpolation = RigidbodyInterpolation2D.Interpolate;
}
void Update()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
float angle = Vector2.SignedAngle(Vector2.right, direction);
if (Mathf.Abs(angle) < 80f)
{
targetAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
}
Debug.Log(angle);
}
void FixedUpdate()
{
// Move the player in the direction it is facing (up after rotation)
rb.linearVelocity = rb.transform.up * speed;
rb.rotation = targetAngle;
}
}
this is what am using all is fine but if i get my mouse on the back side it changes the player's positon in relation to cinemachine
i might be asking yall too much but bro the last project i worked i searched all on the internet and then finally i quitted cuz of the bugs and not having solution after pouring like 8 hours
I am pretty sure you are just gonna tell about SO, but can I like get info from a prefab without needing to instanciate it?
Sure
Oh, can I? Like get the icon of something that is not in scene?
I'm not sure what that means exactly, but sure, it exists, you can access it
It's... hard to explain. Basically items have a prefab that holds their info and also is like the main functions that allow to click them and move it around to equip them and all while in the inventory. I want to still be able to show that info in things that refer to a item but are not really an item that is in the inventory
Im trying to use the new unity input system. I have the notification mode set to "Send messages". I use this function below to capture if the user is spriting. However, the game starts as not sprinting, then when I click shift the game recognizes sprinting. But when I let go of shift, it doesn't untrigger and still says its sprinting. Why is this?
public void OnSprint(InputValue value)
{
isSprinting = value.isPressed;
}
Just @ me if anyone has a solution or a fix
i am not getting OnTriggerEnter2D if i setActive(true) and object while standing still
if i move and setActive(true), the event trigger
anyone encountered this b4?
How do you guys handle the lack of confidence in coding ? I keep rechecking the same damn code even though i already recheck it 10+ times before
A Rigidbody moving is what calls OnTriggerEnter. It doesn't get called if you activate an object that is already inside a trigger, a physics update needs to occur on the object so it checks it's colliders
Just keep coding anyway. The best games all kinda suck in one way or another
Yeah i know but the class is so big that i cant remember every part of it so there is always this unshakable feeling that there must be a bug somewhere (even though i already check it for 10+ times and didnt find any). Idk maybe this is just my anxiety, i need to take some break from coding i guess.
If theres a bug somewhere, youll know in one of 3 ways - either the console will tell you about it at runtime (runtime error), or the console and your IDE will tell you about it before your code can be compiled (compilation error), or youll notice your game is not behaving in the way you intended (logical error), the latter is probably the hardest to deal with but you can use Debug.Log statements (or breakpoints) to get an idea of whats going on when unintended behaviour happens
In terms of having a big script, certainly breaking it down into smaller scripts and making sure that each of your classes are not doing more than they need to (for example, a UI script doesnt need to do any input management), but that will come with time, and getting more familiar with S.O.L.I.D and code patterns (which as a beginner, I think its more important to get things working first in a way you understand)
I think my anxienty came from that one incident where i found a nasty bug from code i wrote long time ago and had to rewrite a lot of code because of it
Luckly it wasnt public API so no backward compatibility breaks
That sounds like it could have been caused by "spaghetti code", where you have one script doing too much or many scripts referencing eachother in strange ways, thats something that gets resolved with time and the latter mentioned practice with S.O.L.I.D and code patterns - but also refactoring (rewriting code) is actually a normal part of development and theres many reasons to do it
Yeah it was spaghetti code
i learned a lot from that but also gave me this anxiety lol
[insert "i simply live with the pain" meme here]
you have to push through, because only with experience will you get good enough. If you're fretting over everything constantly, you're not going to make things. Mistakes are how you learn, you have to do things so you can learn from them
Okay thanks everyone
lack of confidence isn't lack of competence, and same for the inverse
check your work instead of the direct code you write
does it work? are you able to debug? are you able to find info if you need it? etc
I'm an anxious person and it's taken a long time to not to refactor as much, and it's still a constant battle to avoid falling into redoing work
i think everyone goes through spaghetti code a few times at first lol
great first-hand lesson on why you should put some thought into structuring the project
Ok thanks everyone i had to do something irl
(and hey, arguably underconfidence is better than overconfidence)
^ true, its better to assume you CAN improve, than to assume you already know everything (even if you made several games before)
you wanna get data from the prefab itself not its instance?
Also just in general, learning a whole new language is hard, learning programming is hard. Anyone trying to pick it up is gonna struggle and spending the effort to learn a new skill is something to be proud of 😄
ive found a few minor bugs so far in a major enterprise system thats been out there for 20 years. practically every game has their own "bug abuse" community too. hell I even played some games particularly for the exploits.
These things happen. As software grows, so does the possibility for edge cases, especially in a game where you have a ton of systems intertwined. The most you can do is test features as you make them. Experience is what leads you to knowing what to test sometimes.
not fully sure what you meant but maybe static variables would work here no?
break the class into pieces otherwise can get hard to debug
hi, im trying to make a game about a spaceship with planet physics. How would you align the players rotation with the orbit of the planet
planetary gravity is the keyword you are looking for
o7
hello, I made a player walk, is the code good? xd
using UnityEngine;
using UnityEngine.InputSystem;
public class Movement : MonoBehaviour
{
public float velocidad = 5f;
private Vector2 movimientoInput;
private Rigidbody2D rb;
private PlayerInputActions inputActions;
private void Awake()
{
inputActions = new PlayerInputActions();
inputActions.Player.Move.performed += ctx => movimientoInput = ctx.ReadValue<Vector2>();
inputActions.Player.Move.canceled += ctx => movimientoInput = Vector2.zero;
}
private void OnEnable()
{
inputActions.Player.Enable();
}
private void OnDisable()
{
inputActions.Player.Disable();
}
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Debug.Log("Input: " + movimientoInput);
rb.linearVelocity = new Vector2(movimientoInput.x * velocidad, rb.linearVelocity.y);
}
}
does it work as you want?
Well, it can only move left and right xd. I'm asking because in the tutorials they make the player move with much less code.
it can only move left and right because you did not define it to do somethign else
rb.linearVelocity = new Vector2(movimientoInput.x * velocidad, **rb.linearVelocity.y**);
that part is correct though
(also for emphasis in code i'd recommend an arrow on the next line)
maybe they want to move up and down too (some kind of 2d top down)
oh good point, ive been doing sidescroller for way too long
yesyes i know, but I’m not sure if the code is very efficient
doesn't matter at this scale
and why there's a private before the void ....¿
don't worry about perf until one of these two things happens:
- you start having perf issues
- you start counting in thousands or millions
like, what does private mean? this question can go a few ways
Yeah, I really don’t know the difference between public and private.
public means any other class can access the member
private means no other class can access the member (it can only be used within the same class)
the default access level is private (there are also 4 other levels aside from these 2) so technically it isn't required but i suppose it's there just to be explicit
ohh okok, thx so muchh
a few keywords to google for further reading, "access level"/"access modifier"
How can i add component by string with it's name? I've tried to use AddComponent() but ide throwing error saying this method obsolete and AddComponent<>() throwing error bc cannot resolve class name
var itemClassName = itemData.GetRespectiveClassName();
var itemScript = item.AddComponent<itemClassName>(); // cannot resolve
var itemScript = item.AddComponent(itemClassName); // obsolete
you shouldn't be using a string
item.AddComponent(typeof(COMPONENT));
if you have the class you should just use the generic one
what are you trying to achieve? cloning itemData onto item?
Well seems that he wants to get that dynamically so he cant use the generic type
I want to use scriptable object with respective class on object, like class Item and ScriptableObject ItemSO so my target is to get type dynamically and paste it to the object
How are you saving the class item in the scriptable object? Just as a string?
same thing happens with typeof(COMPONENT)
you would do instance.GetType() in that case
I'm losing my MIND, when I grab my weapon's prefab onto my weaponslot in the player's hand, it is fixed perfectly (0, 0, 0) and when i try to do it by code it just give me some weird x y z
i tried resetting it in the code, still weird
show us the code 😄
the prefab itself was a mesh at first, so i added a parent to it, in hopes of maybe fixing it
keep in mind that the position shown in the inspector is the localPosition, not the position
so what's what here, itemData is the SO?
I'm using scriptable object to store default item data and when object already exist somewhere in the world i store it in class so i can modify in one way or another
public void CreateItem(InventoryObjectSO itemData, int amount, Vector2 position)
{
GameObject item = Instantiate(itemPrefab, position, Quaternion.identity);
item.name = itemData.itemName;
var itemClassName = itemData.GetRespectiveClassName();
var itemScript = item.AddComponent<itemClassName>();
var itemScript = item.AddComponent(item.AddComponent(typeof(itemClassName));
}
{
DropCurrentWeapon(pickedUpWeapon);
// Parent it to the weapon slot
pickedUpWeapon.transform.SetParent(activeWeaponSlot.transform, false);
// Reset transform to be at (0,0,0)
pickedUpWeapon.transform.localPosition = Vector3.zero;
pickedUpWeapon.transform.localRotation = Quaternion.identity;
// Mark it active
Weapon weapon = pickedUpWeapon.GetComponent<Weapon>();
weapon.isActiveWeapon = true;
}```
ok yeah don't use strings to link all that together
How should i do it else?
Do you have very few types that rarely change?
If so you can do an enum -> type mapping
so you have an inventory and individual slots?
Inventory store slots and each slot store object with data
ok, and why do you need to create the components dynamically?
what coordinates do you get from the code?
you could just have InventoryObject have a field of type InventoryObjectSO, no need to paste anything anywhere
I havent checked what coordinates the code brings me
i look at the inspector and it has different x y z when it links it uip
At this point i have only 1 SO but what i wanted is to branch it later, like inventoryObject is base script, then goes something like weapon -> rifle -> specific weapon and trying to make it scalable from now
have the SO handle that
have variance in the data held, not the data holder
what does your DropCurrentWeapon do?
{
if (activeWeaponSlot.transform.childCount > 0)
{
var weaponToDrop = activeWeaponSlot.transform.GetChild(0).gameObject;
weaponToDrop.GetComponent<Weapon>().isActiveWeapon = false;
weaponToDrop.transform.SetParent(pickedUpWeapon.transform.parent);
weaponToDrop.transform.localPosition = pickedUpWeapon.transform.localPosition;
weaponToDrop.transform.localRotation = pickedUpWeapon.transform.localRotation;
}
}```
why are you setting the weapon to drop as a child of the weapon you pick up?
Can you elaborate? Can't catch your thought
weapontodrop is the current weapon im holding
i want to de-parent it
so its not a child of my slot
ah wait, didnt see the .parent, if you wanna fully deparent you can just do SetParent(null)
yeab but i'd rather it be a child of the world instead
so it'll just be chilling
ah alright
consider:
rename InventoryObject to InventorySlot
then inside, have a field for InventoryObjectSO (or perhaps rename that to InventoryItem/SO or something)
you could have the SO or an interface have a virtual Use method, then a specific kind of item, like InventoryWeapon or whatever would extend the SO and implement the Use method (or also implement the interface with that route)
i still dont get how my issue persists
@woeful scaffold what even is your issue?
what's the behavior you're seeing from code that you don't want?
i would assume you don't do anything in the setter for IsActiveWeapon? (except for setting the bool)
also, you should probably just store the Weapons yourself instead of using the transform children and then having to GetComponent each time
When I manually place my prefab onto my WeaponSlot1, (0, 0, 0) it aligns perfectly to the hand, but when i try to use code to do so, it doesnt put it at 0,0,0 therefore not in my hand
yeah
that being AddWeaponIntoActiveSlot, correct?
Will try to do something similar, thank you
yes
so if you inspect the gun, you see it not at 0,0,0?
if its by code ,yeah
have you verified that you've saved and recompiled the code with the position setting
i restarted unity to be sure i guess
that doesn't verify that you've actually saved the code
right, that would do it
the method itself is working but the xyz doesnt align well
im not sure what's causing it
in AddWeaponIntoActiveSlot, try adding some logs
pickedUpWeapon.name to make sure you're targetting the right one, its localPosition and localRotation after you try to set it
so it's not working then
wait i wanna take a vid to show u
its acting up
@naive pawn SO like
I press play right, i spawn in as the character, the weapon that i pick up is aligned related to the world position
so if there's a weapon a little bit forward than the middle of the world, when i pick it up it'll be forward
if its perfectly in the middle, then when i pick it up its placed correctly in the hand
wth
im not psychic, i have no idea what you're talking about lmao
ill explain better
the cube/volume icon is the middle of the world
u see the pistol thats slightly on the left and forward?
if i pick it up, its on the left and forward just like it was placed originally
what is the issue
it's not being placed fixed in my hand, it's being placed on my hand + the offset of the world or something
if you inspect said weapon while it's not in your hand, does it show 0,0,0 or something else
the gameobject of the weapon that's supposed to be in your hand
the weapon on the ground that i want to pick up has the X value of 0.317 and z 0.811, when i pick it up it keeps that value
i want it to reset when i pick it up
have you done the logs i told you to do
oh ill dot hat now
hey guys new to unity, i tried following brackey's unity github setup video, am i supposed to have this many changed files?
No. You're missing a .gitignore file or it's in the wrong place
or the git project root is wrong
no, though most of the ones in that snippet are fine. When you setup a GH repo you get a chance to choose a template gitignore
i swear i picked the unity gitignore file, its in my repo as well, lemme screenshot it rq
yeah I keep templates of the ignore and attributes in my GH shared repo
oh wait nvm yeah the root was just wrong
i moved the gitignore file and it works now lol
thanks guys
Did you read what the error says?
yes
Okay so have you tried changing the setting mentioned in the error?
gee, if only the error message told you what the setting is called as well as where it is. since you didn't read it we'll never know
Its almost worrying how many people post that error here without READING IT
!collab 👇
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
oh
Hi everyone, i have a problem with my shader, in unity zero problem but when i build the game , the shader bug like this, can someone help me
#1390346776804069396 for shader issues
you'll also want to provide more details about the issue (see #854851968446365696 for what to include when asking for help)
@slender nymph ty i will move post on there
I am making this feature where when the player which is the ball goes into the trigger zone and presses R I want the Tracking Target to switch to Player 2 which is the cube. I haven't touched cinemachine for a while so I have forgotten some stuff. How would I go about this?
Here is my script and this is what I got so far. > https://paste.ofcode.org/NFwcKegivjZjA6a9fGKhCW
I dont use cinemachine but i would assume there is a call type in script to change the target
change follow/lookat https://docs.unity3d.com/Packages/com.unity.cinemachine@3.1/api/Unity.Cinemachine.CinemachineCamera.html#Unity_Cinemachine_CinemachineCamera_Follow
OR you can change virtual camera when entering the zone to swap camera to one already configured.
hello, is wheel collider's source no longer online?
I don't think it ever was.
Yes, someone once shared a pretty solid base that was the equivalent of the wheel collider. but this is more available
Do you mean the nvidia PhysX source code?
That's right, I'd forgotten about it. Thanks, if I'm not an idiot, Unity's wheel collider is based on that.
i need a bit of help, im currently stuck finding an unsupported shader, however i have no clue how or where it could be. is there any way to make it a bit easier to find? (im sorry if this is the wrong channel to ask this in, i had no clue where else to ask)
#1390346776804069396 open thread and share some more info there
!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.
hello, I just started learning Unity, I have an idea for the game
I started developing with basic movement but ran into a problem with implementation on inclined surfaces
the problem is that when the surface is tilted even by 30 degrees, the player can freeze at a spontaneous moment
here is the code for implementing movement
I am translating through Google Translate, there may be errors in translation
https://paste.ofcode.org/3LqWQVsrzBFuzVdWqGiBaT
rather than just setting a Y position for your target and still moving with the same X and Z, you should instead use the normal from the ground (provided by the RaycastHit) and project your desired movement on a plane represented by that normal. It will get you the correct movement direction.
could you please tell me how to do this or even send me the edited code?
you're also breaking the rigidbody's interpolation by setting its position each time you call SetY as well as when you set its rotation in the loop which can lead to stuttery movement
this is a code channel
oh sh yeah sorry
can you tell me how then should I maintain a strictly defined position relative to the raycast point or should I reconsider this idea in some other way
if necessary I can tell you a little about my idea of character movement maybe you can suggest some ideas
what do you mean by "a strictly defined position relative to the raycast point"
I mean the distance from the beam landing point should be 2f
something like that but without breaking a rigidbody
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit))
{
Vector3 point = transform.position;
point.y = hit.point.y + _height;
transform.position = point;
}
you would just apply any normal gravity and stop it at the ground as normal. then your movement would be projected along the ground so you won't have to manually set the Y position
These are also breaking your interpolation btw
transform.position = target;
and
transform.rotation = Quaternion.LookRotation(direction);
It's just by design that part of the object can end up in the textures, so the center of the object ends up on a point, and if you use a rigid body, it will hang unattractively when the rotation axes are frozen.
Should I try writing a basic collision and movement system myself?
I was wondering how I can change the tracking target depending on the gameobject list I know its something like _camera.follow blah blah but I want it to track the current target index (e.g., 0 for main player, 1 for player2). how would I do it? this is what I got so far and its working perfectly right now https://paste.ofcode.org/4SM56vLh5GQ5542FE4j47z
you´d have to change the cinemachine Follow target
I know but I want it to track the current index. like when I enter the trigger it adds the object in the index which I also want to track
I will be adding multiple cubes where you can change
If you mean simply changing the index reference to switch objects, it's the same idea, but instead of using the object, you use the collection-index set.
Example:
Instead of
camera.Follow(targetTransform)
You do
camera.Follow(MyTransformList[index])
And set the index to the one you need however you need to do it.
Assuming that is how you would set the references/arguments in the first place of course
I meant like. I want it to work with multiple players/switchzones that I can switch to because right now like in the image shown if I go to player3 and press R it will switch to player2
so I want it to work with multiple players/switcherzones.
I am soo confused at this point lol
please explain clearly what you want to do.
Sorry its hard to explain lol. Basically I want it so when I go in the trigger zone the player 2 or 3 depending on which trigger zone I am in should be placed in the list as you can see in the video and when I press R it should switch the player to the one that's it the list and I want this to work with multiple players. get it?
watch the video when I go into the left triggerzone it doesn't take player3 it takes player2
this is the script I made. https://paste.ofcode.org/7DjGQZHdB7JGYh93wV2E3d
well you can have one variable for the target and change that as you wish.
Transform target; << this can be changed somewhere in your code, anytime you want.
camera.follow(target)
you can also fill your List before runtime if the transforms are existing and known
tbh completely honest I am so confused lol been at this for the whole day
So first how would I make it so when I am in the triggerzones it correctly gets the right object and places it in the list?
anyone know the fix to this?
Just to be clear, are you asking for help on what you might be doing wrong?
Or assistance on how to refactor your code to meet the new requirements?
assistance
isnt this beginner code?
there is a reason why these special channels exist
In that case, there a couple ways you could do it.
The most obvious would be making another variable for the player3 exactly how you setup the first for player2 and just add an if condition.
However, if you want this more dynamic to allow for more targets in the future, I suggest having a class on the zone, that the switcher looks for, with a reference so the switcher can read/use it on enter/exit.
How you set that reference is however you want to do it
Could be in the inspector, or even just moving the current find object code to the new class
wdym class on the zone? like make a separate script and make it a public class?
Yes
why exactly shouldn't be used physics movements on Update?
what if i must only use update or fixedupdate
Because the time between updates changes based on framerate and physics calculations depend on things being at fixed intervals.
For example, if you were doing movement in update, and had a particularly large lag spike, your movement when you "caught up" would have a massive momentum from moving so far in one frame
so in the new script for the zone switcher what should be in it? ontrigger enter/exit?
Im new to using the profiler, I found what code is using so much gc alloc, but not sure how to fix it
Anyone willing to help?
In the new script, you don't need to use on enter/exit. You can keep that in the switcher, but when it occurs, check the object for the class.
var zone = other.gameObject.GetComponent<ZoneScript>();
if (zone != null)
{
//DoSomething
}
In the zone class, you'll have a public reference/variable for the object you want to add to the list
https://dontasktoask.com, we can't help without more info
show said code, perhaps
whats the way to post it without being so messy?
!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.
public override void CheckForTransitions()
{
// All the transitions between states are defined here
switch (currentState)
{
// Transitions from Wander to other states
case Wander:
// If is not alive aka dead
if (!isAlive)
{
// Transition to the Death state
SetCurrentState(new Death(this));
}
// If the player is not being attacked by another zombie and the player is within the attack distance
if (PlayerIsNotBeingAttacked() && Vector3.Distance(transform.position, player.transform.position) <= attackDistance)
{
SetCurrentState(new Attack(this));
}
break;
// No transitions needed for Death because once the zombie is dead it doesn't have to transition to any other state!
}
}
is Death a ref type?
also Attack as well
yes they are
do I need to change anything in the main script? https://paste.ofcode.org/mRBfNvFvQBhZtxj9XATDPi
so in the new script I should add what you put?
Sorry for bothering you lol been at this for the whole day still kinda confused
does it have to be?
not necessarily, but i feel that it would make it more difficult
the garbage basically boils down to instantiating a ref type
you could either make it not a ref type or not instantiate a bunch
the former would be turning it into a struct
the latter would be only instantiating the states once and then reusing them
you could also do both, like you might do with enum states
how so?
Ill try only instantiating the states once and then reusing them
i also researched that Vector3 uses some too, is this true?
uses some.. what?
As I mentioned, you'll be adjusting the the OnEnter/Exit already present in the current switcher script.
However, you'll be moving the variable for the object to be added to the list into the new script.
After checking for the zone, you look for and use that reference.
In the new script, if the reference is public GameObject ObjectToAdd
Then you'll use zone.ObjectToAdd instead of player2.
What you'll need to figure out is how you want to set that reference in the new script. Though I would suggest setting it in the inspector by dragging in the object from the scene that you want to use for that zone.
No worries, I'm here help, but I won't do it for you. Otherwise, you're not learning anything
GC alloc
no, Vector3 is a value type.
Im trying to get GC alloc to 0%
that's not possible
every component is a ref type
gameobjects too
you will have ref types -> garbage -> gc
sure it's possible
Application.Quit()
optimization is reducing unnecessary allocations, not removing them outright, because some are necessary
For this project, I have too
do you have a gameobject in your scene?
Let me rephrase, for these scripts, I have to have 0% gc alloc
lofty goals will get you nowhere
gc is not something to be avoided
you should be thinking about unnecessary gc, not allocations as a whole
Then you aren't going to be making any variables at all
Im just telling yoy what the project requierments are
you sure?
yes I am sure
depending on the goal its definitely possible. Usually when people say 0 alloc, they just mean allocated once at the start and none afterwards while playing
I think the goal here is to perform the task without creating new references per frame
this is extremely unreasonable for a project, unless it's something really low level
but at that level you probably just don't have a gc
It is very low level, im just leaning how to use a profiler
the deep profiler would also give you more insight as to what specifically is allocating, though we can see those new Death and new Attack directly do so. You cannot get around this, you must change how this works if you want to avoid allocation there. Or reuse the attack/death state
i don't think "profiler" and "low level" really fit in the same sentence
ok
i feel like you're just trying to use cool jargon without actually understanding the nuances...
you got me
this is really all it is
don't worry about getting to 0% allocs
Whoever made those requirements is trying to get you fired
depending on what they're actually tasked with, it could be very reasonable to expect that certain scripts dont allocate anything after they start up
I think the goal of your task is to refactor this code to not have to use the key word new. This will allocate new memory every time you use it, increasing GC Alloc in that frame.
that's not "no alloc" though. there'll be something to GC at the end anyways
only allocating heap memory for ref types would relate to the GC
we can argue semantics of it all we want, it doesnt matter. when people say 0 alloc they always mean when the game is running, not when the game starts up.
"0 garbage collection" literally means no reference variables. And that includes Unity-defined ones so it can't be a MonoBehaviour either
this is exactly what I mean
Then you can't create any variables, call Instantiate, or call new on any class outside of Start or Awake
Id start with looking at why you need to new a state in the first place. You will need to reuse these states instead and declare it once, possibly in awake. if you have allocations past that, then you should also use the deep profiler. its just a button on the profiler
creating variables doesn't allocate
!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.
Reference variables, I should have specified.
still no
You'd have GC when the object with reference types gets cleaned up, right?
Although I guess it'd never get cleaned up itself huh
that's on the value though, not the variable
Here is a slight fix https://paste.ofcode.org/FTiCvhGuGPKNqwsFCqYHaT
Wsup !
I'm currently into Procedural Generation, here's what I tried.
-> Height Map : That is awesome, but not for caverns like minecraft.
-> Marching Cubes : That works but not really.
Basically I want an open-world like minecraft but without the cubic aspect.
https://github.com/Scrawk/Marching-Cubes I used this Marching Cubes.
and it do what i expect it to do. but there is a space between chunk that i don't know how to solve.
Here's my code : https://paste.mod.gg/oeqifclautmw/0
I am totally new so any advice/suggestion or even fix are welcome !
But Update is still using some gc alloc while running
oh, this answers a lot
FindObjectsOfType<ZombieStateMachine> is allocating
FindObjectsOfType in update
seems like it doesn't have an overload to fill an array or list, neither does FindObjectsByType
but in general you should not have Find* in Update anyways
and that's run for every zombie?
Or, at all. If you can manage it
this should be a static thing
its still reasonable to expect that a lot of scripts dont need to do any of this past awake/start. Like movement logic for example, nothing really needs to be created. Unity helps you too by having nonalloc methods if you need physics checks
So I should remove player2 in everything and replace it with zone.ObjectToFind?
So I commented out the vector3, and it was making about 97% of the gc alloc while running
If that's how you set up the new reference, yes.
Basically, zone.ObjectToFind is your new player2, but now it's unique for each zone
Yeah, zero allocate after start is achievable but very restrictive. I was just pointing out all the stuff that you'd need to engineer out
a static list of ZombieStateMachine that's updated as instances get created or destroyed (or enabled/disabled, depends on how the flow goes)
then PlayerIsNotBeingAttacked checks if any one of them is attacking
or, all this in a manager component, so it can also compute the result for each frame instead of having to do it for each zombie every frame
and how did you comment it out?
if (PlayerIsNotBeingAttacked() ) //&& Vector3.Distance(transform.position, player.transform.position) <= attackDistance)
I think im just going to restart the main script cause I have already coded some stuff and when I remove player2 then loads of errors pop up and doesn't recognise zone.ObjectToFind.
there's nothing allocing here
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector3.cs#L352-L358
you might want to make this a post in #1390346827005431951 instead
thx
If you didn't make/save the new script and reference, then attempting to use the new variable will cause an error
Also, if you're using player2 anywhere else, removing it will cause that error as well
the new script just has public GameObject ObjectToAdd; and in the main script is this https://paste.ofcode.org/ryJDnevt6k65GaM7ku7Vu3
so for this part if playersToSwitch.Contains(player2)) should I remove player2 and add zone.ObjectToFind? I did that and it didnt recognise it
If you didn't add the GetComponent to get the zone script, then it's not recognizing zone beause you didn't make the reference yet.
You can use this to replace your tag comparison
var zone = other.gameObject.GetComponent<ZoneScript>();
if (zone != null)
{
//DoSomething
}
Hey, quick question; how do people add the comments to their methods so that you can see like a description of it when you call it from another class? Tried to google it but didn't know the right terminology 😬
(could omit the .gameObject btw)
put ///
did you try "c# comment docs"?
thanks, couldn't remember, so i put it there just in case lol
oh, makes sense, well, thanks
like this?
pro tip: use TryGetComponent instead of a GetComponent call and a null check. Also it is not necessary to access the gameObject property on a component to call GetComponent, Component implements it as well
Yup, should do fine.
Hey all, can anyone see where I'm going wrong with this please? Baffling the crap out of me as I've used this same controller a bunch of times before, but this time, no matter what I do, my flying vehicle constantly loses height (It supposed to stay a fixed distance above the ground)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
like this? if (other.TryGetComponent<SwitchZone>(out var zone))
you could also do out SwitchZone zone and let the generic infer
yep, or you can make it ever so slightly shorter with if(other.TryGetComponent(out SwitchZone zone))
As for these parts should I also change them to zone.ObjectToAdd?
No, you can remove all of the player2 stuff from the Switcher since the reference is going to be on the SwitchZone instead.
Another tip, you can leave the list check in there before adding/removing if you want to ensure it's not attempting to add/remove the same object twice.
It shouldn't, but I like to be thorough. I'm not sure what kind of bugs can come out of trigger Enter/Exit
as for this part if (inSwitchZone && switcherAction.action.WasPerformedThisFrame()) how can I make a debug.log tell me which one I switched to ?
updated script > https://paste.ofcode.org/tqWGsvRqcnwv9paRFZAmgG
Well, your initial code didn't have the logic for determining which object to switch to from the list. Did you have a plan for that already?
Once that's figured out, you'll be able to use that same reference in the debug log
not really a code question?
ask in one of #1390346776804069396 / #📲┃ui-ux / #💻┃unity-talk
is the player attached to a canvas for some reason?
right now you get a worldpoint, treat it as a screenpoint, and convert that into a worldpoint again
i want to get position in units
viewportpoint is what you want, but the origin is in a corner rather than in the center
you can transform that quite easily
units in what space
i'm getting hard
cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
here
what i want
that's not the player position, but ok
is your player in a canvas or not
yes
and you want to turn that into worldspace
wait
no
if it is not attached to a canvas then its transform.position is already in world space
you said the player is in the middle of the screen and you want to get (0,0) based on that fact?
is that correct?
👍
there's no space that has that behavior, but there is a viewport space that goes from (0,0) in a corner to (1,1) in the opposite corner
so you'd have to do WorldToViewportPoint, and you'd get (0.5,0.5)
you can transform that result with some math
depends on what value you want for the corners ((1,1) or (0.5,0.5))
I already tried it, and I got 0, 0 in the center and ~0.01, ~0.01 in the corner
it's all in 2d with orthographic projection on camera
Yeah im going to do that now just need to change the tracking target of the camera to the player 2 or 3 when in the trigger zone
does it matter?
that's all I do with playerPos
📃 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.
hii everyone
i am a beginner and while holding a key it does not work i have to press it again and again
except that if i keep pressing A on keyboard to move palyer to left and while holding A if i press D, D key does not work. i have to leave A and then press D so that player can move right
You won't be able to input two opposite directions at once
You would have to use Input.GetKey instead of Input.GetAxis
wait do you expect pressing D to go right even when A is held?
i thought you meant it didn't stop
like i dont want to get two at same time
but like i wanna say. i press A to move player to right, but while holding A if i press D it should change its direcion to right
but it doesn't, i need to remove my hand from A and then press D to move it to right
i dont meant to stop it or smth
but like while holding a it moves to left but at sam etime if press d it shoudl chagne direction to right
it was doing thiw but idk how it randomly changed and these 2 problems occured
So, you are expecting it to read two opposite directions at once, which it can't do
Letting go of left to get it to read right is normal
but at sam etime if press d it shoudl chagne direction to right
this.. generally isn't the behavior given
if both directions are pressed it usually results in no motion
yeaa thats what i am expecting
like i dont want it to read both keys at same time. but if i press d then it should read the new input of D instead of the A key
That's not how it works
It's a virtual joystick
You can't input one direction without releasing the other
i mean, you can, but you generally don't
it was moving like this fr
the situation of me rn i talked about just happened randomly and i dont know how
but previously it was moving like that
On a joystick you physically can't, and since GetAxis is meant to emulate a joystick, it prevents you from doing so
i mean you can emulate that behavior with keys/input
yeah, i was making a different point, shouldve worded that more clearly
that's a lot of .GetComponent
cache BallController in a field here, and type SwitchZone.ObjectToAdd as CubeController instead of GameObject
for unity Objects, a bool implicit cast is provided that's the same as != null
you could use that instead if it looks cleaner - doesn't make much difference but just presenting the option
Yeah I think im just going to re do it. a bit messy tbh
saw it before you deleted it, I was also going to say you dont seem to use that playersToSwitch list anywhere. And yea you should rarely be referencing things by GameObject
instead of checking the _camera.Follow, i think it'd make more sense to check the currentTarget because you already have a variable dedicated for this
tbh im so confused. I have the base down already I just need to make it so when I am in any trigger zones and I press R the tracking target of the camera changes to player 2 or 3 depending on which trigger zone I am in. https://paste.ofcode.org/HmsD3GCJ5L4XiXxvLLTKtK this is my script decided to scap the other one
Is there a way to convert a terrain to a plane after some modification (like painting or low/raise of terrain) ? please
you can probably use the FBX Exporter
ur an angel
i was about to create a script to do it xD
its hard to imagine how you're going to be using this script. one thing that i dont understand is why you add these objects to a list, unless you can have multiple zones overlapping in random parts. think about it first in terms of gameplay. Which player should it swap to if there are multiple options? What should happen to the old player if anything?
i imagine you might want to just keep track of the current index if going through the list one by one
And is there a way to like do a terrain, then i want on each side the terrain height is 1 ?
It doesn't work is it normal ? It's just giving an empty fbx 😦
where are the other code channels?
you have to enable them
I looked in id:customize
what am I missing
oh
I have to go to channels
this newfangled discord stuff is hard for an old timer like me
if you didn't already
you can follow them (or whole category) in the browse channels section there so they show up on your channel list on the left
I was just looking for the role that gives it to me
didn't realize I had to enable it
perhaps roles give it too... idk its a bit annoying 😄
I'd rather have it show all by default
Any tips on how to implement toggling on/off Debug.Logs() in a script?
if (debug) Debug.Log(...)
I guess. It would still be included in builds though. If I set it to always false in builds it wouldn't cause any performance hits, right?
ah I just realized my class is a normal C# script, so I can't toggle in via Inspector
is there any way anyone could help? My code for adding a function to my button doesn't seem to be working properly. Also another problem - this isn't with the code and more just with unity itself - when I try and use my mouse to click the buttons, they don't highlight in any way or do anything when I click them. https://paste.myst.rs/8eu19ohp I believe the culprit line is line 124, also please ignore the 3 or so lines after that I was trying something.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Wouldn't you automate it by #if UNITY_EDITOR?
sounds like something (invisible) is blocking the buttons.
hmm okay I'll look into that, do you have any advice about the AddListener thing?
code seems fine, they probably don't do anything because you can't click them. You can check during Playmode if the newly spawned Buttons have an OnClick event added in the inspector
yeah that's what I checked and it says there is no function
I would also recommend to make a class "ChoiceButton" that handles the setup so you don't have to use GetComponent<> a bunch of times
okay, thanks
could the invisible thing be something I have inactive in the inspector because that would be weird if so
You can change the Inspector to debug mode and look at your event system, it should have a field for "Current Focused Game Object" which will be the mouse hover
I also just tested it, a buttons' OnClick event in the Inspector won't display any added events.
okay thanks, so it's just the buttons not being interactable then
in the debug mode it just says no game object is current selected so I don't know what's going on
I don't think so
I'll test that I don't have any other buttons in the scene
ok that took longer than It shouldve but yes in another new scene I made the button worked normally
this was a completely empty scene though
is there any way to call OnMouseEnter() from an object outside the collider? i have a holder with about ~70 different colliders and i want to get the info from whichever one you hover over in one instance
rather than from 70 instances into the 1 instance
isn't there a function like OnMouseOver?
You’d have to re-implement a similar system. I actually did this literally 24 hours ago aha. The code is abit rough and probably not super recommendable but I can share if your interested
from unity documentation
yeah you need the script attached
im talking script outside of the object getting the call from the object
cant you attach a script to each that calls for that other script?
like i know it sounds Weird but i dont know how else to achieve what im trying to do
KISS: Just use a component with a static event, invoke that event in OnMouseWhatever and pass the desired component from the object that method is being called on
KISS?
use the profiler to determine performance impact
look up the kiss principle
will find
i doubt it would be noticeable cause the function is only called once per mouse over
well i've had scenes with 1 million plus objects all with the same script with different function calls running at the same time and keeping 150fps
my pc would fry 💔
Is calling an if statement oncollissionenter with saod script like playercontroller on said if statement, like a gameOver for example static booleon, is that alot faster then finding said player?
who knows it could be different per project, profile it
it basically was an Accidental discovery finding a solution when trying to do the 3.5 segment
Had to do a Booleon with the .gameOver
global ofcourse
guys can anyone help with this problem, i would explain it here but its niche as hell and id spend all day trying to explain it and still wouldnt get it across
can anyone who knows a thing or 2 join vc or smth
its 2d related btw
does this server* even have a vc
idk
i only come to this server when im desperate and couldnt find any solution to a problem
there isnt
is it possible to send a photo of it or no?
if u want we can join any vc
no lol
its a problem while running
or execution ig
i'd rather not
sure use pastebin or something though
whats that
see the bot embed below 👇 !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.
ok
wasn't sure the command :/
using NUnit.Framework;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
public class gamemangerscript : MonoBehaviour
{
public static gamemangerscript instance;
[SerializeField] public int maxheartcount;
[HideInInspector] public int heartcount;
[HideInInspector] public List<GameObject> hearts = new List<GameObject>();
[HideInInspector] public List<Animator> heartanimators = new List<Animator>();
[HideInInspector] public heartmanagerscript heartmanager;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
heartmanager = GetComponent<heartmanagerscript>();
heartcount = maxheartcount;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
if (heartcount == 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
the useful commands can be found in #854851968446365696 if you need them

don't forget to actually explain what you are struggling with
its not letting me send the rest
yeah ik but my msg needs nitro to send lol
again use one of the websites from !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.
use a bin site for large blocks of code like the bot said
its too long
Chat GPT works aswel for problems like this
i tried istg
it gave me solutions that didnt work or were just dumb and executed the same code but in a different way
yh does that, sometimes you got to be very specific though since it only reffrences from the internet
A tool for sharing your source code with the world!
heres the code
basically heres the context
im trying to make a basic heart system in a rpg kindof game so the hearts obviously gotta persist through scenes so i made a gamemanger gameobj singleton with dontdestroyonload() and added the hearts prefab to it as children
the heart prefabs are named "heart1", "heart2", "heart3" exc hence the list sorting and stuff
basically the whole system works fine until the player 'dies' and the scene reloads
then it just becomes a mess
sometimes it freezes
sometimes it tells me that i destroyed the animator component im trying to access?
im not even kidding i think i sat here for like 1 and a half hours trying to fix and at least figure out why this is happening
i used chatgpt but to no avail
kinda at a dead end here if anyone can help with this
Not this advanced yet, but I've noticed if you are trying to specifically do something like isDead etc, you should look into that specifically
wdym
i think it would cause your Awake() in heartmanagerscript may be called before the gamemanagerscript Awake() which causes it add data that is planned to be deleted
where in your code does it state the Character dies basically
no i changed the execution order in the proj settings
the gamemangerscript runs first
-100 priority
and the heartmanager is default
which is 0
Sounds like when you "return" it goes through the "start"
why not just set it as a different function that is called in the gamemanagerscript?
in the gamemangerscript, "if heartcount == 0"
wdym
With Return in the code, does it specifically go to the "void Sart()?
oh and i forgot to mention that the gamemangerscript and the heartmanagerscipt are both script components of the same gameobj that has the dontdestroyonload thing
since you have it in Awake, there's no reffrence to this I think
ok so, you need to seperate them somehow
with a reffrence
separate what
When you die right you have return or something, and you have nothing in start, my guess is that when the code gets read as return it doesn't show in the Awake() if that makes sense
its in the managerscript
ahh ok
it has an update that constantly checks the players heartcount
if the heartcount ever reaches 0 or under it should run
which reloads the scene for now
Can't you reference this directly?
im fairly new to game dev so if theres a better way to do stuff i wont know lol
rn even when im trying to make an effort to make the code organized its still spaghetti
yeah the gamemanger is set to -100
the heartmanager is set to 0
oh miss read :/
ur good
use Debug.Log
well there aint any here
Have you tried putting the get componants in the start the ones that when you lose hp etc
since return forces the system to get for Start
their in awake does it change anything for them to be in start?
I believe it does yh
doesnt it js wait until everythings instantiated
also you gotta clear these before you open a new scene with the gameobject saved
[HideInInspector] public List<GameObject> hearts = new List<GameObject>();
[HideInInspector] public List<Animator> heartanimators = new List<Animator>();
Awake is basically when the game starts, but Start is where you put the Return value componants into for it to read it again, I think anyways I maby just overlooking etc lol
i would assume this is then why you get the errors about missing data
or that yh
i tried .clear() 'ing them before reloading the scene at the death check
is that the same or do i need to destroy the gameobjs?
did you do the same with the 2 in heartmanager?
you wouldn't no
heartmanager doesnt have anything
it takes everything from gamemanager
it has 2 lists
no it just assigns the lists that were initiliazed in gamemanger
its ok lol
can you show the error logs that display
is this what game dev feels like
sure
It's problem solving
Took me 3 days to come up with a solution about a problem with my code lol
its crashing and the game is frozen
spent weeks on the same problem some times it's gets painful
but this is the inspector
its not crashing crashing where i have to end task
but its really really really slow
and this is the first time ive ever seen this (is loading) thing
im geniuenly baffled a heart system can take this much time to do
I think my eye twitched there 😅😂
asked for this one stinker
well yeah you have to run the game and die to get the errors you were talking about
yes ik
thats what happens when i die
it loads and goes into a crashlike state
and doesnt show anything in the console
does the gamemanager object have alot of objects in it?
it has js the three heart objs
and wait whats the point of making it not destroy on load when you destroy it when it loads?
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
thats there to prevent duplication
or there being more than one instance
but it'd delete it
im pretty sure
why
cause when you load the instance the second time wont be null so the else passes and delete this object
but then wont there be 2 gamemangers?
thatll mess things up cuz theres 2 instances now
2 seperate blocks of data i think
which is why you should make it not be MonoBehaviour and instead have a different script call the load scene
having it not be MonoBehaviour means you can't make it a component on an object which limits it to one by default
well you could just have it be nothing but yeah
well it just sits there and can be referenced by anything without having reference a component in the scene instead you just call gamemangerscript. whatever variable here
but i want to like be able to keep info between scenes
it will always keep the data through scenes no need for a DontDestroyOnLoad
how would that work without a dontdestroyonload
really?
how do i set it up
just remove the MonoBehaviour and Awake, Start, Update functions
and put
heartmanager = GetComponent<heartmanagerscript>();
heartcount = maxheartcount;
into their own function thats called through heartmanagerscript first
and itll js hold info?
yeah in memory
the gamemanagerscript couldn't no
the heartmanager though yeah
i dont really get it
here give me a minute
so does it stay as a script .cs file in the project folder?
yeah
and if i set every variable in there to a static tag i can js access it whenver i want to and itll persist through scenes and stuff?
yeah
yh Tags are quite helpful with this
something like this https://paste.mod.gg/sbaefcsydfyj/1
A tool for sharing your source code with the world!
though you might need to tweak it a bit since i dont have access to your project
ohhhhh
i get it
basically ur just using it as a medium for carrying info for your game
thats actually perfect
thanks for the help
only problem is you wont be able to see the variables in the inspector so you'll need to set them in code for the heart count
Anybody know what the point of “lists” are??????? What makes them different from arrays and how I use them every time I use mine it gives me an error I just don’t understand what I’m doing wrong
lists can be expanded while arrays cant
So like you mean an array has 3 and can only be minus and lists can be at 5 but go up?
Like “randomlist.Add(1)”
yeah where when you declare an array it's fixed at the size but a list cause have more data points added to it
You can add things to a list
Ohhhhhhhhh wait so like a list you can set it to 1 but then you can add 3 BUT if you do it with an array it can’t it’s only a fixed number?
me when thats what i said 
The video I watched on it didn’t say that
I didn’t understand the video I watched he didn’t give good examples
it's a fixed number if indices
but yeah
started in september
just under but yeah
Ok that makes sense why u prob know stuff
I started 2 weeks ago 😦
😦
Why it not let me
could you send a photo of what you are trying to do?
Oh im not on unity rn i was asking the question because im sitting in my bed watching videos to understand new concepts
well you learn as you go it's a big field you'll always be learning new stuff no matter how long it's been
True
I think I’m decent though I can do functions and if statements
And variables and logic
I’m able to code a sword swing script
And a sword purchase script
🙂
nvm this post xD
ooooo my bad ! will write it there, cheers ! 😄
You are correct in that it will be controversial outside of that area
I can see why, but for me it was a great tutor for now regarding very small things 😛
This is kinda of a generic doubt but like, can I just have like several classes on a single script? Like how does that even work when assigning it as a component? Would it just act as all classes on the script? It's the name of the script just the name of the top class by default but I can have all I see fit?
You can’t with unity objects (monos and so’s) (unless they are abstract since they won’t show up anyway)
You can with others (base classes, structs, interfaces etc.)
So if I have like a support class that it's not meant to be used alone as mono I should just place it on the same script, but for everything else I should be using a new one right?
Up to you. If it's only ever used for a specific class then you can even make it an inner/nested class
So basically I wanna do a Serilizable class which sole purpose its to map a gear slot to a gear type and make it seriazable so I can edit it inside of a list in the editor
I am guessing those kind of stuff go inside the script as a new class
You can serialize nested classes too but there's usually some limit to the depth
more of a limitation of Unity's inspector
but if you want to make a bunch of serializable classes that are just data containers, you can make like a single script and throw them all into it if you prefer that method
otherwise SOs are an alternative if you don't mind asset bloat
I do mind asset bloat, precisely for that I am asking if I can avoid making more and more script assets lol
That does seem usefull if I am gonna use them over the whole project, but for this one in particular I don't think it's the case, so I'll keep it on the class
private Dictionary<string, object> publicData { get; set; } = new();
public T GetPublicData<T>(PlayerDataConstant.PublicDataType type) => (T)Convert.ChangeType(publicData[type.ToString()], typeof(T));```
someone told me if i use pattern matching on this function it would be faster/better , but how?
the dictionary must be in the form of <string,object> due to API restriction
any reason why Convert.ChangeType? just curious
you asked about perf but that particular Convert.ChangeType is actually slow
how many types will be in the dictionary? Does a simple switch-case wouldn't do the job here
also you may want to try-catch there
i think i found a better way now , ty 👍
i just gonna convert every data i retrieved into their suitable type
foreach (var(key,item) in await CloudSaveService.Instance.Data.Player.LoadAsync(PlayerDataConstant.PublicKeys))
{
publicData[key] = publicData[key] switch
{
PlayerDataConstant.PublicDataType.UserID => item.Value.GetAs<Int64>(),
PlayerDataConstant.PublicDataType.Lv => item.Value.GetAs<byte>(),
_ => throw new Exception("retrieved data failed to convert! ")
};
}```
this should be better, plus this function only called once after player login successfully
IT WORKED 😭
pls can someoen help me out
Devs lääh ❤️
hey can anyone help me set up a basic third person player controller with cinemachine?
a lot of tutorials with cinemachine are very old and the ui has been changed so i cant really do much
I think plenty of people have already told you that using get-axis, you'll not be able to move right if you do not release left etc
i didnt understood it at first that why i was nto able to fix it
hi guys, can i ask why my sprite is so low quality and compressed in the image
Not sure but you could try setting filter mode to point instead of bilinear.
ah okay i think i got it
i did that and also changed the compression thing on the side to none
which shoulda been kinda obvious in hindsight
and make sure to import your sprites in a normed size like 256x256 / 512x512
also im not sure if i just imported it in wrong or what
i just dragged it in from the file explorer instead of doing right click import new asset
that doesnt matter but the size is very important for the compression
regarding the image size: NPOT means "non power of two" so it cannot benefit from certain formats that greatly reduce size (dxt, etc)
when i build the game im getting "cannot create FMOD" error
i dont get it in the editor
have you tried to google it?
i found quiet a few tbh, seems to be something obvious
hey guys im really new to programming and unity. can anyone give me some advice on the best way to learn c# via unity?
there are beginner c# courses pinned in this channel, then the junior programmer pathway on the unity !learn site is a good next step to learn how to use c# inside of unity
I personally recommend learning c# separately first because you will then have an easier time learning to use the engine since you'll already understand the basics of the language
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you so much for your advice
on avg how much does it take someone to become a junior level game dev?
like from scratch
sorry for my bad english
oh yeah i found results but not a lot for my problem
hey i want help
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
i learn't basic c# from the brackeys c# basics series but i still don't know how to code as in i can not code in unity but i cant tell what he is do ing but i don't know how to code myself
hey does anyone know how to get vscode to detect unity errors and such, i'm returning to a project after a long while and vscode has just decided to be annoying
i can only do it useing the .NET frame work
!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
• :question: Other/None
thank you
does any one know how i can learn how to acually use c# in unity
there are beginner c# courses pinned in this channel. then after you understand the basics of the language i recommend going through a unity course like the junior programmer pathway on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
it is much easier to learn c# separately from unity because you'll get an understanding of how the language works without also needing to try and learn how the engine works at the same time
what is the actual error
Error: Cannot create FMOD::Sound instance for clip "FinishTypingTrimmed" (FMOD error: Error loading file. )
dozens of this
previous builds were find
fine
but now it gives me this
and have you googled the error? the first result gets some pretty useful information
yes
great! then consider reading that information
but the only ones i found were the error is in builds are 0 answers stack overflow threatds
and if you need further help then see #854851968446365696 for what to include when asking for help
I had already done everything that was stated here and the problem persists so idk what else to do
FMOD is a third-party sound asset. It shouldn't be in your project unless you downloaded it.
i didnt
incorrect, unity does use FMOD for its audio
there is also an asset for more of FMOD's functionality in the project though
bruh i found like 7 different threads for that problem and not 1 has an answer