#💻┃code-beginner
1 messages · Page 705 of 1
have you tried debugging outside the if
that couldnt happen because the debug log did happen
Debug.Log the collision first
idk what that means "debug log did happen"
you know your setup better than me, you have to explain what that means in this context
yes it didn't work
show the inspector for both player / wall
and where you place script
this script is not on any object with the collider
also curious, y does the wall have a dynamic RB
actually youre right, i dont think talk is being set to true at all
now its just a matter of further drilling down where its going wrong
can't it work on the parent instead of the child?
Ye
no it needs to be on object with collider
if parent had rigidbody itself for example it will work cause its all 1 rb
why not put it on the player and check for walls that are destructable Tag or something
Yeah imma do that instead. I have no clue why I was doing it this way lol. Got a bit excited
Hey yall. So I wanted to get started with Unity. But i always get this Error: Could not find Unity Package Manager local server application at [D:/Unity/6000.1.14f1/Editor/Data/Resources/PackageManager/Server/UnityPackageManager.exe]. Missing files could be the result of an antivirus action or a corrupt Unity installation.
Click on Retry to relaunch Unity and reopen your project.
Click on Diagnose to launch the Unity Package Manager Diagnostics tool.
Can anyone help me? I deinstalled it multiple times now and i deactivated the antivirus i had on. Im lost....
Actually no talk did get set to true. I put in the update function if(player.talk){ debug.log("should display") } and it did show but not every frame after talk should've been set to true. i also put if (!player.talk){debug.log("not displaying"), which i commented as it is showing every frame and only if i commented it i could see "should display" being printed
either way works its preference but imo easier to just have 1 script instead of many of them essentially queuing the same event
*actually,no.
(Not "no talk did get set to true", i meant "actually, no.")
huh I don't get it
Should i send a video or sm
if (player.talk)
{
Debug.Log("should display");
dialogueBG.style.display = DisplayStyle.Flex;
}
else
{
Debug.Log("not displaying");
dialogueBG.style.display = DisplayStyle.None;
}
this is what i put in the update function
just explan a bit more ,
and "not displaying" got printed out constantly every frame. but "should display" also get prints everytime only when i hit 'x' which triggers the dialogue
so this possibly means that after talk gets set to true it gets set to false straight after
i think
seems so
now ill dive in more
wait no
but it doesnt make sense
the whole dialogue is being called normally
the machine never lies
Makes sense to me. Update runs every frame, no?
if you have something like
if(inputKey) talk = true
else
talk = false
Guess what, its being set right away back to false
I mean it's right there
Why does it says all compiler error have to be fixed to enter play mode when there are no compiler errors and i saved it
check what the compiler errors are?
Show your console window?
hi, for a weird reason when i try to use my Codex, this message appears
MissingReferenceException: The object of type 'UnityEngine.RectTransform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
i definately changed everything that refernce the deleted die() function
and saved it
lovely you didnt show line 53
trigger and manager should probably be serialized references btw
what do you mean
my Codex what does is just delete and spawn the tabs needed, but why is falling?
public or [SerializeField] class fields that are assigned in the inspector
yes?
they aren't assigned in the inspector in the code you showed
i don't see the declaration, so can't say if they're serialized fields already
yes, im saying they should be serialized references instead
oh may i ask why
Find is somewhat fragile, it uses magic strings
you should avoid it (and magic strings in general) if possible
that makes sense thx for the advice
also intensive, imagine making a list of everyone in the world and asking each one if they are your neighbor
how would we know
have trigger/manager as the types they were before, not GameObject
you don't need the GetComponent in Start
but why does it work for manager and not trigger?
no clue, you shared your code in an ass format
true my bad
im not gonna look through that grainy screenshot any more than i have to lmao
trigger and manager were probably declared as GameObject instead of their respective types
ops my stupid discord just updated didnt see chris already said it
What does cs0104 'debug' is an ambiguous reference between 'unity engine' and 'system.diagnostic'
Hey, still working on that UI? The message describes the issue well, you have a reference to something that was destroyed so either do not destroy it or update the reference to the new instance or check for null before trying to use.
shit just realized the same question was posted
A class named Debug exists in both namespaces and it can't tell which you want to use
i mean, i was told to better ask here
sorry
but yeah
thx and what is the difference between them
ends up a Codex is a lot harded than i thought
alr well yeah keep coding questions in code channel
did you see anything i wrote in #💻┃unity-talk
yep im trying to do that rn, but in case it may dont work
one is for Unity and one is for System.diagnostic
now im realizing, is when close the Codex when this happens
what do you mean
many things im sure. The problem is that you have a using statement for System.Diagnostics in the file. You can delete this if its not needed or add:
using Debug = UnityEngine.Debug; statement.
didn you said to make it less redundant?
Oh so i dont necessarily need system diagnostics rught
nope
Oh ok!
I mean it works 100% if you follow correctly, but that can be done after you solve issue
ok
redudant code just adds more noise to a script
also, worst part, is when i skip the error message, the game plays just fine
As you learn more about programming with c# and unity it will be easier to make stuff like that and also debug errors and issues.
its plays "fine" but it affects all the lines that come after the part you're accessing null UI item from
o h
If the error is only when you close/destroy the UI it may not actually break anything
even if it seems fine you shouldn't have that because you have a flaw in the design
er I dont think thats fair to state rn
It could be easily fixable and not really matter
also something i found now, is that.....saved entries persists.. BETWEEN TESTS
i mean, i made it to unlock an entry for test how would look...and now despite i deleted all ways to unlock it, remains unlocked
its an easy fix, just make the design better.. Dont access things after they got destroyed lol
m a y b e i s r e l a t e d ?
How do you save and load save data?
thats the fun and creepy part, i dont do that yet
only thing with memory is the DDOL object
It may be you are modifying a scriptable object which will keep changes post play
which is bad and you should stop
DDOL shouldnt run between runs.. you got something else goin on
remember the "wiki assets" you made a few days ago?
and i only use it for the asset
cryptic
literally everything i did, was following for the tutorial for making Ui's
If you are sure you dont modify them thats good
did you store objects in the SO ?
cause if you did, don't lol or at least clean them up after
i use the SO like a kind of plain for the buttons
i mean
this is the so script
is it possible to assign a uidocument in the inspector window? because it keeps saying reference is null
[CreateAssetMenu(fileName = "CassielDictando", menuName = "Cassiel/Journal Entry")]
public class CassielEntrySO : ScriptableObject
{
public Sprite Foto;
public string Nombre;
public string descripcion;
public int categoria;
}
that doesnt answer the question , wdym plain for the buttons
i make assets based on this, and paste them on the singleton
oh as long as you dont store things from scene in it you're fine
what are you on about
wat
nav, not you
huh? wdym ?
the last issue was data saving between sessions but we can see the scriptable object type doesnt hold this data
I presumed it could be the cause but thats not the case
I literally just saw what their SO does lol I saw SO mentioned and asked if they stored scene items not sure what was confusing
the only UI items they mentioned being destroyed was buttons, I'm still putting my money on they getting accessed after being destroyed, perhaps living as null in some collection. No idea as half this code looks AI
I see starchild has asked about a topic that began yesterday elsewhere. much effort was spent trying to help them with some ui code but different people saying different things each day doesnt help either side
I recommend opening a thread in #1390346827005431951 and keeping discussion there
ok
I'm answering without prior context so yeah maybe they should have a thread if they are asking about the same system someone else on this discord suggested to do
I just saw the "RectTransform was destroyed while you trying to access it " error and suggested where to look into
yea missing context confuses all sides 😆
Its okay, when we don't know its hard to ask the right things or know what to try
I deleted that line of code but the same old bug occurs: talk is set false straight after ,and also i made the ui document public and assigned it in the inspector window. Thats all i changed
Actually, now the dialogue panel just shows up straight away but "not displaying" is still getting printed
So i've added a bunch of stuff to my character controller script since this morning, and although it's not as bad as before, i'm still noticing some slight inconsistency with the height at which the capsule jumps by looking at the position on the Y axis. It's not outrageous but i'd rather eliminate if possible. Here's the code : https://paste.ofcode.org/NpqFX9xzuqyBh2uVyvdd4P
Not sure what mistake I made this time
Hello, are there any websites for codes in C# pls ?
start:
var enumerator = map.GetEnumerator();
int idx = 0;
foreach(var kvp in map)
{
if (math.distance(pos, enumerator.Current.Value) < viewDistance)
{
if(idx > results.Length)
{
viewDistance = (ushort)(viewDistance / 2);
goto start;
}
results[idx] = enumerator.Current.Key;
idx++;
}
}
Is using goto bad? that looks a lot cleaner to me than
// Retry loop for adaptive shrinking of viewDistance for this cell
int attempts = 0;
const int maxAttempts = 8;
bool cellDone = false;
while (!cellDone && attempts < maxAttempts && viewDistSq > 0f)
{
int idx = 0;
int count = 0;
foreach (var kvp in map) // assume kvp.Key is the result key, kvp.Value is its position (Vector3/float3)
{
// compute squared distance
Vector3 diff = pos - kvp.Value;
float dSq = Vector3.Dot(diff, diff);
if (dSq < viewDistSq)
{
count++;
if (idx < results.Length)
{
results[idx++] = kvp.Key;
}
if (count > results.Length)
break; // overflow detected early
}
}
if (count <= results.Length)
{
// fits; done with this cell
cellDone = true;
}
else
{
// too many: shrink and retry
attempts++;
viewDistSq = (viewDistSq / 4f); // equivalent to halving viewDistance: (viewDistance/2)^2 = viewDistance^2/4
}
}
pinned in this channel
Thanks
goto can lead to unintuitive flow so it's generally recommended to be avoided.
i feel like this comparison is kinda unfair though, the second block is doing so much more work
its doing the exact same thing
the end result is the same
definitely not, kvp isn't even used in the first block
all that extra work is required to avoid the goto
enumerator.Current.Key;
is kvp.key
nope, separate iterators
nope
the foreach structure gets its own enumerator
oh my mistake
I sent the wrong code block
var enumerator = map.GetEnumerator();
start:
int idx = 0;
while (enumerator.MoveNext())
{
if (math.distance(pos, enumerator.Current.Value) < viewDistance)
{
if(idx > results.Length)
{
viewDistance = (ushort)(viewDistance / 2);
goto start;
}
results[idx] = enumerator.Current.Key;
idx++;
}
}
+ while (true) {
var enumerator = map.GetEnumerator();
int idx = 0;
foreach(var kvp in map)
{
if (math.distance(pos, enumerator.Current.Value) < viewDistance)
{
if(idx > results.Length)
{
viewDistance = (ushort)(viewDistance / 2);
- goto start;
+ break;
}
results[idx] = enumerator.Current.Key;
idx++;
}
}
+ }
```this is all you need to remove the `goto` from the first codeblock
(it seems like faulty logic - like this was a half-finished version - though, so it probably won't work. im just using that first codeblock to demonstrate)
i have went a long time assuming break breaks out of all current loops
nah, just the current one
some languages even have labelled breaks (and continues) for finer control, unfortunately c# is not one of them
we dont talk about goto 🎵
right now i have a loop, inside of a loop, with two more loops inside of that.
yuck
NativeParallelHashMap<Cell, NativeParallelHashMap<ushort, float3>> entries;
public bool QueryPosition(Vector3 pos, ushort viewDistance, ref ushort[] results)
{
var cell = Cell.FromVector3(pos, worldData.cellSize);
bool foundAny = false;
int baseX = cell.x;
int baseZ = cell.z;
for (short dz = -1; dz <= 1; dz++)
{
for (short dx = -1; dx <= 1; dx++)
{
var neighbor = new Cell
{
x = (short)(baseX + dx),
z = (short)(baseZ + dz)
};
if (!entries.TryGetValue(neighbor, out var map))
continue;
var enumerator = map.GetEnumerator();
while (true)
{
int idx = 0;
while(enumerator.MoveNext())
{
if (math.distance(pos, enumerator.Current.Value) < viewDistance)
{
if (idx > results.Length)
{
viewDistance = (ushort)(viewDistance / 2);
break;
}
results[idx] = enumerator.Current.Key;
idx++;
foundAny = true;
}
}
}
}
}
return foundAny;
}
any suggestions to clean this up?
why is the enumerator being itterated without foreach?
and im sure you know while true is not always a good idea
this also seems to not be beginner code
sure it is
its really not 😆
ok noted ill use foreach
but that really not going to clean it up any. Its code for a spatial hash
it's definitely not a good idea in this case since there's no exit from the outer while loop, this code will loop infinitely
im still finishing it up but yes there will be a "max attempts" condition
What the code is doing is looping the collection and returning any that are in neighboring cells and within "view distance" and if there are more then the length of the results array reducing the view distance and starting over
why use the native parallel hash map? I assume this is going to be jobified at some point so you might as well do that now
I will if the benchmarks show this as performance critical code, but in the network update loop I am using this collection inside of a job
whats the different between:
public static IEnumerator SaveCoroutine()
{
var task = Task.Run(() => Save());
yield return task;
}
``` and
```cs
yield return new WaitUntil(() => task.IsCompleted);
wtf is that first one
both of those look like landmines for the unsuspecting
wrong channel
They're more or less the same the second one just allocates a WaitUntil
bet thanks
If you want to run something on the thread pool ideally you use UniTask instead and then await it instead of trying to mix coroutines with async
How many times should Random.InitState((int)DateTime.Now.Ticks); be used?
Idk can you actually yield return a Task?
my bad where do I send that I'm new
I'm not sure yet can
It's for a roguelike.
Once? When you want to reinitialize the Random with a fresh seed?
bro can you stop being a bitch?
it can yield loadsceneAsync operation so i assume this also can
dude says hi and you''re in here complaining
I wouldn't assume that
You should check
Yo be honest though there's no point in either yield here
Because you're not doing anything after the yield
My code has that line before the boss decides an attack and I'm not sure if I should remove InitState from all across my scripts.
im planning to use this somewhere else with
yield return SaveCourotine
I don't see why you would do that
Generally rogue likes aim to be deterministic after the initial loading/seeding process
Gotcha
anyway to do it with pure courotine? im not allow to use thread in this project yet
Task.run uses threading so you should just call Save() normally
Task.Run uses a thread already
yea
but the game would freeze right
best change it then
You can read and write files with UnityWebRequest funnily enough
That'd be the most Unity native way to do it
why not just do this in reverse
you can use the async io functions instead but who says you cant use threading?
start with a small view distance and increase until the array is full?
yeah, so no restarting required
I was under the impression that Unity would keep generating the same number without multiple InitStates but then I saw a thread that suggests otherwise.
i feel like it would lead to a lot more iterations
i mean, in a way, yes
prngs are deterministic, with the same input (state) they'll yield the same output
the trick is to use part of the output as the input
starting big and going smaller would only lead to more iterations if there were a ton of items in the same area which isn't going to happen often
i mightve misunderstood the purpose of the map then. is it not cell->value?
actually wait - is cells to values 1:1?
its a spatial hash its a cell with a list of values basically
NativeParallelHashMap<Cell, NativeParallelHashMap<ushort, float3>> entries;
ah i see, i misunderstood
essentially i am getting the current cell of the camera, looping through that cell and 8 surrounding it then looping through each item in each cell
another option (more straightforward but more work) would be to get all the neighbors' values and sort and get a range, but that might be significantly more work depending on the size of the result list and amount of items
Yeah unfortunately thats the issue i am running into. This query command is called once every 66ms by every person connected
(could be made better by sorting each area to get only the result count of items and then basically doing a merge sort)
ooh, yikes, yeah thought it'd be less frequent lol
i should probably just job it and sort them tho tbh
I'm pulling my hair out with this error here regarding my code reading an asset and taking that asset and modifying the button prefab into that card.
It's able to read the card in the initial script, but when I attempt to do a setup function in another script it fails to read the cardName
hi i am using unity first time and can someone help me with loading textures to my city becasue everythingis purple?
Hard to tell what's going on here without knowing filenames or like numbers
!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.
send code not screenshots
I'd say probably card is null
Since you're reading it and never assigning it
You're doing card = c after you've already been using the card variable
That needs to happen first
You do card.something 3 times before ever assigning it
yeah that was it
I was calling card.Cardname not c.cardname
I'm passing c as the obj
not card
I can see that
that was the issue
could someone help me with my inventory system? I'm trying to make a system where saved or disposable inventories can be created at runtime. I have an abstract InventoryBase class and then concrete inventories inherit from that to add their own rules (food cant go into gear inventory, etc). I want a generic inventory UI controller but i'm having issues figuring out the best way for it to be able to hold any InventoryBase type. https://paste.mod.gg/molnyhyxtnyt/0
A tool for sharing your source code with the world!
right now every inventory will be saved as the abstract type. I want a clean way to choose what type the UI controller should use, maybe like a dropdown in the inspector. However, I don't want to use serializereference since im creating random inventories at runtime
I wouldn't use inheritance for that
Just a tagging system
The inventory slots can have whitelist or blacklist of tags
could anyone help me with this problem where my sound effect plays a second late when the player first moving, it like have a delay when the player first start moving. Im using the input system to detect the player input
The timer starts at the interval and you check if it's under 0
So yeah, it'll have a step interval worth of delay
+whatever empty space is at the start of the audio
Is there somewhere I can go to find an in depth code review on something I think can be done better?
chatgpt only helps so much and tbh half the time its bad advice haha
how would I code it
is there any rescources I can learn from
can't really do it with no clues, I've never touched shaders before
How do nested prefabs work when working on a team project?
Hmm perhaps with a noise tex/generated noise that scrolls on x and y
then using step restrict it to some parts of the noise to create the outline effect?
You probably need to start with something simpler to learn the basics
There is no special behaviour, if you change the same prefab you are going to get merge conflicts, if its simple changes you can easily merge them
What's the best workflow me and my team can have for editing the same prefab?
Should I duplicate said prefab and apply changes on my version, then we can combine em?
split the prefab into smaller chunks
if you have a current problem be more specific and its easier to help you
Just trying to mitigate future merge conflicts
Is duplicating the prefab and working on my own version the move?
you will need to copy all the work of the other person afterwards
That's fine if it's safe
it is safe, but not easy as you cant really compare the two
you would have to manually go through each value
I would advise against it, if they just move a gameobject to the left, ok thats manageable, but anything beyond that and you will not find every change
oh right thank you
Also, I have another question, how can I make it so that when someone repeatedly presses buttons like a d a d or w s ws the sound won’t play multiple times?
Create another timer to prevent that case
Can you recommend any specific tutorials/documents/websites to read?
Unity learn has some stuff on using shader graph.
https://learn.unity.com/pathway/creative-core/unit/shaders-and-materials/tutorial/66fc4313edbc2a0023a2538a
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
It's mid way through a pathway so may be good to do it all
what pathway?
also does shaders affect UI?
I found some tutorials on how to do a 2d shockwave effect with shader graph and I was wondering if it would also do the uplift effect thing on the ui
using the blend tree but my character isnt playing the animations despite it showing it on the blend tree, the bool saying moving is true it just stopped since i took the screen shot
although it is playing in here but not on the game scene
i dont understand why at all
haha figured it out
i had accidentally made a second animation layer and it messed it all up
nice bro
Hey! A question, is there a way to check betwern a range of numbers?
What i want to do is to disable objects between 90 and -90 degrees rotation usually i check if objects are bigger or smaller than a certain number but for this situation i cant do that :<
(If the rotation is 90>= and =<-90) so i transition between 180 and -180
Maybe use dot product instead.
I dont quiet understand the dot product, how/what am i using it for?
it can tell you how much 2 vectors are in the same direction
= 0 -> orthogonal (angle difference = 90°)
> 0 -> in the same direction (angle difference < 90°)
< 0 -> in opposite directions (angle difference > 90°)
and if they're normalized as direction vectors would be,
= 1 -> parallel (angle difference = 0°)
= -1 -> antiparallel (angle difference = 180°)
Additionally: i'm currently having my objects snap to my mouse and hover them over a ground. However the object is halfway stuck in the other object, basically dragging object 1 through object 2. Is there a way to avoid this or os it better to adjust the pivot point?

in unity I have the strangest bug, when I am making top down movement, when i click repeatedly my movement keeps going for a few seconds even when i stop. i have tried and the error still persistent: in a new unity scene, when using getaxis, getaxisraw, and getkey, in a build, and the input settings are still default (im using the old input system).
Have you set the layer order ?
gonna have to show some !code about how you're moving the player
📃 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.
no its just the input. in my update function, regardless of whether its getaxis, getaxisraw, or just the actual inputs, it still does it
this stil does it in a blank unity scene
Vector2 direction;
void Update()
{
direction = Vector2.zero;
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
direction += Vector2.left;
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
direction += Vector2.right;
else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
direction += Vector2.up;
else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
direction += Vector2.down;
Debug.Log(direction + " | " + Input.GetButton("Horizontal"));
}
well this is not what you should do instead of GetAxis/GetAxisRaw
yeah but it happens regardless
what does "direction" do? is it used to change velocity or add force?
no that wasnt the full movement script, that isnt the problem, its the actual input. it prints the right values until i start clicking, then my inputs get held for a bit when i release the directions.
the movement script is not the problem ebcause it happens here too in an empty unity scene, but in the original it is used to move position, with pos += direction * speed * deltatime
the movement script is not the problem because it happens in an empty scene
those 2 things just are not related
are you using a rigidbody, and what's the actual movement code
ah wait skipped a few words
this seems like maybe a hardware issue
have you tried a keyboard test site to see if that replicates the input weirdness you're seeing
What is the good practice to move an enemy with rigidbody? (AddForce vs MovePosition vs velocity)
Never touch velocity
So both AddForce and MovePosition are decent methodologies?
Addforce is what i am using
fsm?
Finished stats machine
Like a function that covers all cases?
Yeah like patrole, chasing, confus
yeah okay
My plan was to first make the dragonflys move in the space
like random dir for 0.5sec, stop for 0.2s, look around swiftly for 0.5s, then speed up to some other random dir for 0.5s
then I had a raycast so that when they "look around", if raycast hits player (they see the player), they speed up to the player
Wdym by character controller? (for the enemy)
wdym by confus also?
Hmmm I dont think i did
When i' setting layers the one with higher prio will be rendered on top of the other?
Yep if I remember right
Player disappears from the patrol vision
I have to test that once i'm back at my setup! Thank you
May be i am wrong as i am still biginner too haha 
Yes it does
I have multiple layered grids
I changed the prio for rendering some on top of others
sometimes changing the order in the hierarchy in the viewport doesthe trick, but it's somewhat inconsistent in my experience; whereas layer ordering always works
You do? Cuz thats something I actually also wanted to do cD
I just dunno how to have more than 1 grid system active lol

hii

For instance you can see in the Grid parent object that I have 4 tilemaps
it's not super optimized performance wise
but basically I have the shrooms on top of all (bonuses), then the walls/obstacles, then the walkable brown ground, then the dark green background
Ugh
We cant do it in other ways ?
You can create a lot of layer and in layer you can also set priorities

Oh yeah i find it, you can do it with only one tilemap

velocity or forces are fine for dynamic or kinematic rigidbodies
moveposition is fine for kinematic rigidbodies (it doesn't obey collision)
position is for teleportation rather than normal movement
velocities are fine wdym
So should I use velocity for "linear" movement and AddForce for "burst" movement?
I agree that position is for teleportation
also CCs are kinda orthogonal to rigidbodies. you can use a rigidbody with a statemachine/casts just fine
CCs?
there's not really any recommendation in that aspect
Character controlee
I don’t know, my teacher tell me it is not recommended to touch the velocity
right don't parrot stuff without knowing why
there's no physical issue with setting velocities
Oh I thought it will
as the docs say - setting velocity can be jarring and unrealistic, but games don't have to be physically realistic
Wdym casts? (statemachine I got is an enum with elems as states so that we manage the enemy through a switch statement (?))
raycasts & friends for detection
Doesn’t it affect the physique of unity if you do it in the update ?
not really
it's processed in FixedUpdate anyways
it's the time-dependant forces that need to be in FixedUpdate
oh okay, first time I hear casts for raycasts
I have a bit of a hard time knowing when to Update() vs FixedUpdate() tbh
basically Update() for player input and FixedUpdate for consistent physics?
Update is per frame, FixedUpdate is per physics tick
consider whether the thing you're doing is frame-bound or physics-bound
for example, inputs are frame-bound, but continuous AddForce is physics-bound
i mean, it kinda is
Is it affected if your game lag ?
things happen in sequence, if the frame takes a long time then the physics tick will be delayed
it'll try to catch up by running multiple physics ticks per frame if the frame takes too long
but computer speed is finite so if the physics tick takes longer than the alloted time then it'll never really catch up
i don't know how that situation is handled actually. what im thinking of would lead to the game freezing completely 

I think the fixedupdate is not executed with the update so if the update is freezed or slower than expected, the fixedupdate is still executed
no, computers can't do multiple things at once
the update has to finish before the fixedupdate can happen
My little brain can’t understand

Oh
Yeah you mean right , unity will catch the time update freezed then executing fixedupdate n time
Before going back to update
how can i make sure that Start method of one object will be called before other?
what about using Awake() for the one you want to run first?
https://docs.unity3d.com/Manual/class-MonoManager.html
this also may help
thanks
you should use awake instead yeah
SEO is per-scene and isn't easily analyzable - it could lead to unmaintainable code
tru, that was just the first thing I found when googling the problem
No. It can create confusion when debugging. There are a lot of way to ensure proper execution order without modifying it outside of the code.
oh but how can I do if I want a particular script execute before all awake?
Use method that executes later https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
Or chain them properly so you know which goes after which
hmm without context, it will be hard , the only one I want it being execute before all is the CoreManager that contain my customLogger.

So if you have a clear chain you should have managing script activating them through reference and not have several scripts running awake

you mean, I create a script that will execute all other script it self in the order i want and leaving empty all awake then create a function Init() to init the script ?
Something like that yes
Switching to explicit initialization order might be better longer term, but it's fine to use the execution order system. DefaultExecutionOrder class attribute is another way to set the execution order.
I would worry more about it with your gameplay systems. Logger needing to have earlier initialization is probably not very surprising.
is it okay to make OnApplicationQuit static?
gameplay systems ?
Why would you need to
im a bit silly and tried to use monobehaviour behaviour in a static class
Then you should stop trying to do that
Those are mutually exclusive options
Keeping naturally flowing call chain will help to instantly see how everything runs in what order. It's also perfectly fine taking advantage of rigid overrides for call order, but it's better to do when you have established structure that you know won't change. Or for tools. TextMeshPro for example overrides theirs.
text.fontStyle = FontStyles.Italic;
How do I specify both FontStyles.Italic AND FontStyles.Uppercase?
I think it's not an enum flag. I'd rather not use rich text tags for this
I am doing right now the game struct so I try to optimize it from the start so later I won't getting problem hehe thanks you 
In TextMeshPro they are flags. You combine them to set them. https://stackoverflow.com/questions/1030090/how-do-you-pass-multiple-enum-values-in-c
#⚛️┃physics question. But generally you use joints/hinges to have multiple rigidbodies be part of one system.
oh I know it haha but forget the name
isn't they trace the trajectory then if it hit something then it will replace the object at the collider position (something like that)
Thanks it is indeed!
FontStyles.Italic | FontStyles.UpperCase
how to generate perlin noise sprite really quick? like i need at least 60 fps
job system
There prolly a much better way to do it but chatgpt looks to have given you a pretty good starting point
[BurstCompile]
private struct GeneratePerlinJob : IJobParallelFor
{
public int width;
public int height;
public float scale;
public float offsetX;
public float offsetY;
// flattened result: index = y * width + x
public NativeArray<float> result;
public void Execute(int index)
{
int x = index % width;
int y = index / width;
float fx = (x + offsetX) * scale;
float fy = (y + offsetY) * scale;
float2 sample = new float2(fx, fy);
float n = noise.cnoise(sample); // returns in [-1,1]
n = (n + 1f) * 0.5f; // normalize to [0,1]
result[index] = n;
}
}
so Mathf.PerlinNoise is too slow?
no clue i assumed you tried that and confirmed it was a bottleneck before coming to ask how to keep it at 60 fps.
I have this issue where it spawn's another player also I am getting a lot of error's on handle menu.
what line of code is throwing the null reference?
i just need for it to be really fast
It cost is equal to your screen size like weight x height so qhd will cost more than hd. How about pre generate sprite then load sprite ? Did it cost more to load a sprite than creating a sprite ?
33 which is the Handle menu
I dont know whats wrong with it seems okay to me
copy and paste the full exception text in here it goes deeper than 33
Then use the job system.
it is assigned tho
In the prefab that gets spawned?
You need to look at the new player clone tht is spawned, not the same obejct that was already setup..
ahhhhh
your right
need to get rid of the clone lol
I see thanks!
because all those things look like you've assigned them in the scene, so are only valid for that instance and **NOT **the prefab
you want to generate a random noise image every frame?
that sounds like a seizure hazard - and really uncomfortable otherwise
Hello, I'm a training manager for ASTM. I've been bumbling around unity trying to animate and build a materials test. I have the project done, except I can't get any usable performance on Web. I want to prove, unity could be a good option to educate. Can anyone help me get my single scene working?
Hey! I'm new to unity and I made a script where the gun will look towards my mouse cursor, but I encountered a problem, at certain positions the gun starts sliding. I assume this has to do with if the collider is in a slope. How could i fix this issue?
if you have a web build to share you can do that, otherwise share some performance information such as your current framerate and drawn triangles from the "Stats" box
this is a code channel, and your question sounds like #🌐┃web is better suited
oh derp it is
not every
but i mean for it to look like in fnaf 1
camera static?
and yes, i know that in fnaf 1 it was just 8 sprites looping
isn't perlin noise meant to be like, a gradient
gradient?
that's very different to static
camera static from fnaf is just some form of noise but scaled
it has random hot spots and cool spots but there's a gradient between then instead of jarring transition, no?
i dont know how it exactly works
but it could be octave noise
Continue the conversation in #🌐┃web or open a thread in #1390346776804069396 .
Your screenshot should show the game view too...
my point is it probably does not achieve the right effect as camera static
because a static signal is more noisy than perlin noise, i guess? im probably misusing terms
maybe, but it still noise
"noise" just means a space with random values
camera static would probably more accurately be white noise
but its kinda like inverted
this is from original fanf dump that i made
strange
oh yeah that's not white noise then, given it has those linear splotches
but it's not perlin noise either, it doesn't have interpolation
maybe noise biased to low values and stretched to give the horizontal smearing lol
Could probably take white noise, expand the dark areas, then stretch it to get the fnaf effect
ok thanks but i dont kinda understand how to achieve this
just a few looping images would be easier and way more performant than generating it all at runtime tbh
i noticed its being like black BG, and some "stains"
but i want to make ones myself
why?
Pre-make some, save them, use them to loop over.
It's really not worth the performance hit to do it realtime
a naive but probably very inefficient way would be to just generate a random value for each pixel/region
how do i make it
pre-make them
perlin-noise isn't that expensive in 2D. You could procedually do that no-prob no?
might even give some bias towards darker values lol
and it will look like crap (i tried tbh)
there's where google is gonna be your friend
that's what tv static basically is
not exactly
in the absence of a signal, noise is interpreted as the signal
to make realistic tv noise you need to make an algorithm that will decode video from random values
Is it okay to use PlayerPrefs for settings or should I use a file
an image from a random noise signal is just a random noise image
there wasn't compression then
it was all 1:1
For settings, definetly playerprefs
i wouldn't say definetly, but it's ok yeah
use whatever, but keep in mind that PlayerPrefs is saved to the computer's registry
How can I turn the selected graphic into a 2d touchscreen mesh for cancelling out point touches?
it's leaning because the game is half down orthographic
you want to exlude edges of the screen from raycast graphics? Using Unity's UI?
bump
where's your code?
you fix the issue by finding out why it's moving, then.. stop doing that
using UnityEngine;
using UnityEngine.InputSystem;
public class Movement : MonoBehaviour
{
Keyboard keyboard;
private Camera cam;
[SerializeField] private float movementSpeed = 1f;
[SerializeField] private Rigidbody2D rb;
private Vector2 movementDirection;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
keyboard = Keyboard.current;
rb = GetComponent<Rigidbody2D>();
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
if (keyboard.dKey.isPressed)
{
rb.linearVelocityX = movementSpeed;
}
else if (keyboard.aKey.isPressed)
{
rb.linearVelocityX = movementSpeed * -1;
}
else
{
rb.linearVelocityX = 0;
}
Vector3 mousePos = (Vector2)cam.ScreenToWorldPoint(Input.mousePosition);
float angleRad = Mathf.Atan2(mousePos.y - transform.position.y, mousePos.x - transform.position.x);
float angleDeg = (180 / Mathf.PI) * angleRad;
transform.rotation = Quaternion.Euler(0f, 0f, angleDeg);
Debug.DrawLine(transform.position, mousePos, Color.darkRed, Time.deltaTime);
}
(its probably highly uneffective ik) But i dont think it has to do with my code and more so with the engine itself
(I was not using the movment keybinds in that video)
I would assume then, that your collider is a box? and that rotates with the gun.. so you're then on a corner of it perhaps, while it tries to use gravity to pull it back flat and keep the angle you put in the code
Not a box but yes, I belive thats whats happening but im not sure on how to fix that
depends on how you want it to act
easiest solution is to disable graivty when the buttons aren't pressed?
Or freeze movement on the rb
Well the whole game is touchscreen for iOS and there are 100s of different sizes, I've got it reshaping around the 16:9 format (in the 2d obscure graphic) but I need it to cancel physic hits on black (usuable) border.
There might be a suitable mesh collider maybe
Ah alright ill try that thank you!
I presented my game to my nephew and it's the first time he's seen a game I wrote
My newphew found that annoying, my brother was disappointed touch happen off the game screen
how can i perform something on first frame? not on load
PlayerPrefs are one of the worst designed features in the engine imo. I would use json.
before or after first frame?
on first frame
because if i start scene preload, it will preload when i preload first one
Start();
Start is performed on First valid frame when the object is enabled
so it wont execute upon preload?
you can change the script execution order https://docs.unity3d.com/560/Documentation/Manual/class-ScriptExecution.html
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
don't think that's particularly helpful
what do you mean by "preload"?
I have AsyncOperation that holds preloaded scene
the point is to make it seamless
ah, gotcha
Awake is called when the GO is loaded and is active
Start is called when the GO is loaded & active, and the component is enabled
with the async scene load, the GO won't be active until the scene fully loads
I've actually got a question for you regarding collision if you dont mind
just !ask , don't ping specific people for help
: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
thx
[In Unity2D] I have an bulletObject that is being fired into an enemyObject. Both have colliders and a Rigidbody2D. On the bulletObject, I have an OnCollisionEnter2D function that destroys the bullet when it hits the enemyObject. The enemyObject has a basic chase script that uses MoveTowards() to track my playerObject.
Before shooting a bullet, the pathfinding works like it should, but when the bullet hits the enemy, the enemy stops moving towards the player and kind of just spazzes out. Is it because of Destroy(bulletObject) adding a force to the enemy that could be messing with its movement or could there be something else I'm missing?
you'd have to 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.
Bullet's Script
public class BulletScript : MonoBehaviour
{
private Vector3 mousePos;
private Camera mainCam;
private Rigidbody2D rb;
public float bulletForce;
void Start()
{
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
rb = GetComponent<Rigidbody2D>();
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position;
Vector3 rotation = transform.position - mousePos;
rb.linearVelocity = new Vector2 (direction.x, direction.y).normalized * bulletForce;
float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + 180);
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
}
}
MovePosition doesn't obey collisions, btw. i don't remember if it detects collisions..
I think i know what happened, you should reset the velocity of the enemy
wait that's not what you said you were using
Enemy pathfinding script
public class EnemyChase : MonoBehaviour
{
public GameObject playerObject;
public float enemySpeed;
private float distance;
void Start()
{
}
// Update is called once per frame
void Update()
{
distance = Vector2.Distance(transform.position, playerObject.transform.position);
Vector2 direction = playerObject.transform.position - transform.position;
direction.Normalize();
float aimAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.position = Vector2.MoveTowards(this.transform.position, playerObject.transform.position, enemySpeed * Time.deltaTime);
transform.rotation = Quaternion.Euler(Vector3.forward * aimAngle);
}
}
I was going to do that, I was just wondering if there was a different way
why are you moving the enemy object using the transform if it has a rigidbody on it?
also by moving it using the transform any forces applied by collisions and the like are completely overwritted so the rigidbody's velocity is irrelevant here
even the bullet, shouldn't that be rb.rotation = ...
eh, that line is in Start so it really isn't going to make a whole lot of difference there
although it would make it simpler since only a float would be required instead of a Vector3
is there a different way I should be moving anything with a rigidbody instead of transform?
via the rigidbody
yes, move it using the rigidbody using velocity, forces, or the MovePosition method
Changing by the transform is like make the gameobject teleporting 
ah, so treat it similar to my player using rb.linearVelocity
so anything I want to move with a rigidbody should use it for transformations, and transform should be used for anything without it
anything I want to move with a rigidbody should use it
yes
transform should be used for anything without it
not necessarily
the issue is that the rigidbody wants to control the transform, that's why you shouldn't modify the transform
that also applies to anything else that wants to control the transform
you mentioned that MoveTowards would ignore collisions, should I still be find using that or is it not good practice for pathfinding
i misread, i thought you said MovePosition on the RB
MoveTowards is unrelated
but yeah with an rb you would probably have different math
is there any way to have _rank and _type ( which are enums ) use the name rather than index
( using ToJson )
they aren't using index, they're just using the actual values
enums are named integers, the integer is easier to process
You can get the name based on the enum value and save it as a string
Just remember to use the string to get the enum when loading back . . .
the cleanest way to do this is to use newtonsoft and write a custom serializer
that sounds like a lot 😭
its pretty simple and documented very well
It's simpler than you think . . .
Though, I do agree with @naive pawn; using the integer value is easier . . .
i mean you technically are asking to save something that's orthogonal to the actual value
i'd say it's a pretty reasonable amount of effort/complexity for that goal
its a lot easier than any hack you can make to make it work with unity built in json
i think i might just have some comments in the default JSON file so users can know which number is which
and a whole new library
whats the struct
you're trying to impose technical debt on them lmao
I have this issue where when I switch to a different prefab that I am supposed to switch to the previous player isn't destroyed any ideas? https://paste.ofcode.org/qstwuezTD37BRBLAb9PpEu
its a whole ass class, featuring other classes from the class may class series
some snippets i think
well that'd be better than going through the enum every time, i think? if it uses reflection every time with no caching, at least
I think script logic ? How do you make the swap ?
public static dictionaries are p cool i think
Some easy ways to see if it work, go debug mode in unity and attach vscode to unity. Add a break point on the destroy then run your game
btw just making sure, you can write to private fields using JsonUtility if the field is serialized right?
btw
bc i need this nightmare to be generated during runtime, hence the use of JSON in the first place
[JsonConverter(typeof(StringEnumConverter))]
public Status CurrentStatus { get; set; }
this is all you gotta do to make it work if you use newtonsoft
have you tried debugging the currentPlayer in Start?
anything can write to private fields with reflection. serializefield is unity's way of marking things that should be written to
wdym by reflection btw
you can also provide the string enum converter when serializing/deserializing (newtonsoft json)
i told this man that 5 minutes ago he doesn't want to use it
thats a shame, its probably the fastest one in c#
*she, and im still weighing all my options
reflection is a mechanism to access and modify language constructs, generally bypassing typical static compiler checks
what is there to weigh? newtonsoft is in the engine already. the built in json is using newtonsoft and its like the industry standard.
the Type you get from typeof(SomeClass) is part of reflection, for example
no how would I do it in my current setup? I use different tags for the prefabs like the main player is Player , second prefab is FastPlayer and last prefab is FastPlayer.
oh its already that?
its a wrapper around it
the unity json serializer is okay but is missing some features. newtonsoft json is known to be the best for c# in general. If we had later .NET we could use System.Text.Json
it's an entirely new api surface
private void Start()
{
currentPlayer = GameObject.FindGameObjectWithTag("Player");
+ Debug.Log($"currentPlayer: {currentPlayer.name}", currentPlayer);
canvas.enabled = false;
}
is it not using newtonsoft internally? pretty sure it is let me look
Err I dont know about that
im going to shake unity i need that it sounds cool
that's.. not what i said
im saying newtonsoft is a new api to learn for ave
not a new library to add to the project or whatever - idk about that
Ahhh a find 
yeah it probably should be a serialized reference
yeah it's probably getting the wrong object since a child of MainPlayer seems to be getting destroyed here
is it this same problem again where you were referencing the wrong object?
Holy shit dude your a genius. Im so fucking dumb the main player was tagged Player and the mesh was also tagged Player. LMAO
been stuck on this shit for 2+ hours lmao
well it depends of its even that complicated
just debugging the object would probablyve told you that
🔨 find bad
yeah you should just use a serialized reference
Welcome to the complex world of NewtonSoft
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
As soon as you said getting the wrong object since a child of MainPlayer seems to be getting destroyed here I got a mini flash back of me adding the player tag to the mesh lol . Thanks for the help
wow that apple is old dont buy it!
When do we use find function ? 
generally you should not
there's always a better alternative, and usually that alternative is pretty easy and involves removing code
its perfect for game jams when you cant be assed to code properly
Hum that what i think too
Its slow and requires an object to exist with a special name/tag
very unreliable
only place I use it is on startup in non monobehaviors that I dont want to pass 900 items to in the constructor
and then you spend 5x the time debugging why something isn't working only to find you mistyped the magic string 😆
the alternatives are almost always easier than actually using Find
But it scan all objects on the scene ? So in a big scene you will just freeze
FindObjectOfType<>() is better as its using a component/object type but it shouldnt be used too much
you can find assets too
i dont recommend it
true but thats the true gamejam experience
if you're doing it on startup whys it matter if there is some loading time
How to kill the cpu
Hmm yeah, maybe 🤔

Where unity saves my file that i wrote by just doing StreamWriter outputFile = new("savefile.json");?
In the build
, idk 🤷
yeah no that just doesn't make sense
no
in the editor, iirc that just goes to the project root?
you should be able to just find it in file explorer
It a joke , don’t mind it 
learn to be serious
what about release build
im not gonna go trough 2.5 tbs of data
Ugh
and savefile.json is just too common
Maybe in your root unity file?
Ah then i don’t know, maybe you need to specify the path for the build
string path = Path.Combine(Application.persistentDataPath, "savefile.json");
using StreamWriter writer = new(path);
ok
Hi! so i want to get the name of the item im hovering over and setting a bool to true, but it the logic still runs even after im no longer hovering over the item
public void Update()
{
//Methods
Clicked();
// Not long enough for a method
// Only update MouseRayHit if something was actually hit
if (RayMouseCast.LatestHit.collider != null)
{
MouseRayHit = RayMouseCast.LatestHit.collider.name;
HoveringOverGun = MouseRayHit == "Cookie";
}
else
{
HoveringOverGun = false;
}
}
this doesnt show how you find
ray logic
public class RayMouseCast : MonoBehaviour
{
public static RaycastHit2D LatestHit;
void Update()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero);
if (hit.collider != null)
{
LatestHit = hit;
}
Debug.Log("Your ray hit" + hit.collider);
}
}
all you're doing is checking for a collider, nothing else to say "display this things name"
You need to check if that game object is one you want to display a name for.
Either using a 'tag' (not very expandable)
or TryGetComponent<T>()
guys im getting into unity and creating games but i dont know where i could learn c#
!learn 👇 -> and check the pinned msgs
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
check pins
thank you
how can i use a method from a different class in the current class im using?
Choose the best way to reference other variables.
ive, tried the getcomponent, but it doesnt seem to be working.
what do you mean not working?
the method is being called, but the code inside the method isnt happening. Im not sure..
is the Shooting script on PlayerPos?
on the children
what is inside method ? did you verify with a Debug.Log
i used a breakpoint
wait.. Detroy() if u destroy the gameobject does it continue running the rest of the code?
yea marks it for deletion and gets removed on the next frame
well, the breakpoint like worked soo..
well wouldnt u want to use GetComponentInChildren ?
so its running?
btw the default editor is the Project Folder, that has the solution.
for a build its where the exe is.
with that said, you should keep things consistent and actually use the folders designed for this, unity lets you do this with the method mentioned Application.persistendDataPath
thats a goodpoint let me try this. Ill get back if it still doesnt wrok
Well the break point like stopped the code when the condition was met
i have no idea where you put the breakpoint so I can just tells you if it hits a breakpoint it means that part reached
exactly, so the method is reached, but its not doing the thing inside the method
// put in OnCollision method to debug the results
// im thinking the Component isn't where you're looking
Debug.Log("Hit: " + collision.gameObject.name);
Shooting myShootingScript;
myShootingScript = PlayerPos.GetComponent<Shooting>();
if(myShootingScript != null)
{
Debug.Log("We've gotten a Shooting script");
myShootingScript.shootBlue();
}
else
{
Debug.Log("Couldn't get Shooting script component");
}```
^ have u actually gotten the Shooting component u believe you have
and what would that be ?
i tried to swap these around, and now its just not colliding/being destroyed after the collision
How do i check the name of something my character collided with?
these are the code
so you put a breakpoint inside shootblue() and it hit ?
inside the OncollisionEnter2D ShootBlue();
ohh..put a Debug.Log after CanPortal and see if it hits that, if it does its running all the lines
^ yup.. couldnt agree more.. debug the entire flow ->
nvm, i just tried it again, and now the breakpoint isnt being hit
heres what I would do for sanity: debug each step
// we collided
// heres what we collided with
// getting component from:
// did i get component or not? // running method
// method ran
It is pointless doing a GetComponent<T>(), just expose a new field, and assign it in the inspector.
^ i was also gonna say soemthing lik ethis.. since u already have ur PlayerPos cached.. and thats what ur apparently trying to get component from
i dont understand
sorry im quite new to coding im not sure i understand what expose a new field means
public Shooting playerShooting; <- do that and assign it in the inspector
then just do playerShooting.shootBlue();
okay thanks, ill try that
As you don't need this to be dynamic, there is zero need to be doing a getcomponent every single time
yup yup, at first i thought it was a mistake and they were trying to get the component from the collision object.. but since its not and being called from the same place everytime just make it a variable
when i put a breakpoint on the collision, collision is happening
breakpoint on calling the method is breaking.
breakpoint on the first line of the method, and now its no longer colliding?? :/
like the gameobject isnt even being destroyed
when you say "method" in that explanation are u refering to teh collision method or the method ur calling in the 2nd script?
the method im calling in the shooting script
i.e ShootBlue();
lol. weird if u call the method it should run teh entire method
when i put a breakpoint inside the method, the collision just stops working
it'll only call it once tho.. b/c OnCollisionEnter is only called on the frame of the collision
1- You need to also be checking your console for errors.
2- Did you assign that in the inspector?
this one isnt being called
did you check if it even reaches Destroy ?
cause it can hit that line with breakpooint you can just check if its null from breakpoint (you hover playershooting)
I'm willing to bet there's a NRE
aye, then ur error is probably there
yeah most likely
:headnodkitty:
nope its not reaching destroy
yeah so that line is throwing NRE
but it was reaching destroy before i put a breakpoint there
I want to spam this.
forloop that junk
lol
i did check console and what should be assigned in the inspector?
What did the console say
nothing
ohr yeah its assigned
did you leave the breakpoint ? we cant see what you see lol
While in play mode? After you call whatever function you're trying to check?
yeah i left the breakpoint in
yes, theres nothing abt the function im trhing to check
did you hover over PlayerShooting. part of the breakpoint.
if you did not hit Continue on the breakpoint hit Unity console would not print NRE for that line until you did. So You can just let the rest continue and check unity console after , hovering the PlayerShooting on that line would also tell you if its null
ive got to go for like 10-15 mins. if any of you are still online, ill try more things then.
thanks for the help though, much appreciated!
it says its null, but im not sure what that means?
probably because you never drag/dropped the component in the field
which field?
the one you made for PlayerShooting
oh ok
wait how do i assign it, nothing is showing up when i click it
Imagine putting a label on a box, but never putting anything in the box
but, when i try and find the script, the inspector changes to its parent
is it supposed to be defined as a script
you can drag the whole object inside or lock the inspector
why not, as long as it has the Shooting script on it
you have to describe / show whats happening , we dont have eyes on your pc lol
inb4 the script not being added to the game object
well well
is it supposed to be defined as "shooting" or "script"
oh rightt, ok lemme try put the prefab into it
oh good spot I didnt see it was a prefab asset
i cannot put prefab object either
pleas use a proper screencapture next time, that motion made me almost fly off my chair
shareX or OBS
I think windws has built one too with snip thing or 🪟 + G
oh im sorry, for some reason my pc screenrecording wouldnt let me send in discord because of file size
it does (WIN shift S)
too large and i dont have nitro
would you mind if i just screenshared to you?
okok ill do that next time
as long as it shows a CLEAR screencapture sure
ill just screenshare my screen and you can tell me what you want to see haha
oh nahh thats too invloved lol
explain a bit more what you want to do , in terms of what object does what and we can take it from there
no point of suggesting a fix if theres a better way to do it, you just have to explain what exactly is the end goal here
cause otherwise you need https://unity.huh.how/references/prefabs-referencing-components
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
^ yes read that
so basically, im shooting a bullet, and then the point in collision i want to set my portal transform to that collision.transform
read that page because you lack critical understanding
ohh so the bullet places a portal
pretty much
whatever spawns the bullet is already in the scene no ? so that link should help you pass the reference through when you spawn the bullet
im not sure, i understand
do you want to see the code?
did you look at the link sent?
Pass the component from the Player that has teleport script to the bullet when you spawn it
thats what i had right at the very beginning no?
i tried to get the component from thr player
is the Shooting script the telporter placer?
yes
originally, i had a raycast, and it would just place the portal on the collision of the raycast. But now, i want it to do that, after a bullet collision.
Pass the component from the Player that has teleport script to the bullet when you spawn it
//player
Shooting shootingScript
shoot()
var bullet = Instantiate(etc..
bullet.shootScript = shootingScript;
^ just handing off the reference
hmm prob better use a method so you can do something you need to
bullet.GetShootScript(shootingScript)
what does var do? i dont think ive seen this code before?
would this code go into the bullets, code?
it just auto detects what the type is if you explicitly say so after
its like telling someone "give me a tool from toolbox" and doesnt matter what the bring, it becomes that tool
var x = 5; tells the compiler: “You figure out what x should be,” and the compiler says, “That’s clearly an int.”
oh ok that makes sense
Ideally here it would be BulletScript or whatever type you have on your bullet
never need to store prefabs as GameObject if you have script on it, store it as that specific type
"BluePortalBullet"
ok that makes sense

not enough info.. which type of character ?
My player, i wanna check if it collided with a object with a specific name
lol you literally said the same thing
what type of character is your player ?
Rigidbody ? CC ? Custom ?
rigidbody2d
Yeah but i want a codition to happen if the name of the object is something specific
sure but thats pretty fragile, its usually a good idea to check for components (script)
If it has a script attached to it you mean?
mhm
Alright ill try to figure that out thanks
{ // has script }
else
{//its not what we want}```
https://docs.unity3d.com/ScriptReference/Collision2D-collider.html
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
you can also search Up parent or children if collider is not the one with script but parent/child does, but that involves multiple lines with
GetComponentInParent / GetComponentInChildren
Can Unity's JSON serialization work with 2d arrays?
naa
wrap it in class/struct
use json.net tbh. its better, also supports dictionaries and others
dude what the fuck is going on here
negative scales 0 scales fckin with the rendering
how would i fix it and or find the things in the negative
okay nows its just gone?
litreally changed fuck all
thanks btw haha
frame debugger can be used to figure out stuff like this (if you have some base knowledge to use it)
#1390346776804069396 btw this is a code channel
Hi folks! I have 2 phones: phone 1 has higher specs than phone 2, but the sprites are twitching really bad on phone 1, and really smooth on phone 2.
https://www.reddit.com/r/Unity3D/comments/18eqedy/excessive_bloom_on_nonemissive_material_with/ it actually has something to do with the shaders most of the time
Sounds like frame rate dependency.
it seems to be something to do with dividing by zero.. or bad values for the shader/materials
we have no idea if you don't share setup
here's my update() https://pastebin.com/a0cQApNF
I also have Application.targetFrameRate = 60; in Start() on one of my objects
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
iirc 60 fps will not do anything on mobile, i believe unity caps it at 30
i take that back, last time i had that happen it was actually b/c a gameobject got scaled to 0 on one of the axis.. totally blows out the screen in that white
in what way is it twiching btw? I do see a Tween but that usually accounts for delta iirc
that is weird as fuck
thank you all for the help! ill be sure to not do that lol
ya.. flashbanged me first time it happened
honestly lol
sorry for late response. It's probably a device issue, I had my mobile OS updated and that's when the twitching started.
a sprite's fill from top to bottom twitches back and forth, normally, it smoothly removes the fill from top to bottom.
it's just weird that other games like vampire survivor that has so many animation works just fine.
IDK if that's a question thats considered beginner but:
Is there a way to combine scriptable object with localisation strings?
My idea is to have my scriptable object with a description of my object, depending on what language i want to print that language. Somebody know how/if i can do that?
It would help if you record a video demonstrating the issue, as it's not entirely clear what issue you have.
anything is possible.
btw unity has a localization package can also look into that
I know that unity has these string tables if you mean that
here's how it twitches
and here's how it normally looks (both editor and other phone)
I really don't have other phones to try, but it's probably a device issue, right?
or am I doing something wrong on my Update()?
try testing Unity with framerate set to 30
sorry ik this is the code chat but how did you find that? Its happaning again for me and i cant find it
it has something to do with my lights im so frustrated. Looks like it is fixed but then on runtime its broken
is there a way to only make a input detection work once?
Set a boolean after you detect it the first time, and only do the thing if it's un-set
Many ways. Hard to say what's appropriate without seeing what you have now.
I'm having an issue where if I have more than one enemy in a scene, I can only destroy one of them, like the other is unaffected
Enemy Health Script
public class EnemyHealth : MonoBehaviour
{
public int health;
public int maxHealth = 3;
public SpriteRenderer enemySprite;
public EnemyChase enemyChase;
private void Awake()
{
}
void Start()
{
health = maxHealth;
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
Debug.Log("Enemy Health: " + health);
}
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
enemySprite.enabled = false;
enemyChase.enabled = false;
Destroy(gameObject);
}
}
}
Weapon Damage Script
public class WeaponDamage : MonoBehaviour
{
EnemyHealth enemyHealth;
public int damage;
void Start()
{
enemyHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyHealth>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Enemy"))
{
if (enemyHealth != null)
{
enemyHealth.TakeDamage(damage);
}
}
}
}
well your problem is how you handle the enemy health you are doing it incorrectly
instead of doing this in start
enemyHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyHealth>();
as a beginer i was wondering whether id have an easier time with unity or unreal engine
do something like
enemyHealth = collision.GetComponent<EnemyHealth>();
in the collision
cause currently you get the first known instance of the enemy not all or the one that is meant to take damage so if you hit one enemy the other could take damage
alright, lemme see
wrong channel, though i doubt there is a correct one fore this
oh sorry
thank you, that seemed to do it
just to check it should look like this
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Enemy"))
{
EnemyHealth enemyHealth = collision.GameObject.GetComponent<EnemyHealth>();
if (enemyHealth != null)
{
enemyHealth.TakeDamage(damage);
}
}
}
yup, I got it to work with that
thank you
This is still an issue! Aparently layers didnt fix it :c
Movement systems are pretty hard to make. Mine features procedural animations for foot placement, leaning, and changing spine rotation based on the speed of movement and slope you're running on, it has acceleration and deceleration with editable AnimationCurves to change the speed over time for acceleration and deceleration, it also has thresholds for the difference between feet positions, speed, and a bunch of other factors before IK applies, and it has animations for hard stops, soft stops, and manually animated transitions between states. It also has things like variable rotation speed depending on how fast you turn the joystick and how big the delta of the transform's forward vector and the input vector is. How good is my movement system compared to a AAA game for example? And is there anything else i could do to make it better?
I'm struggling a bit with coroutines. My plan is to have an button that starts an event after like 3 Seconds. What am I dong wrong:
(``` public class DisableAndEnableButton : MonoBehaviour
{
[SerializeField] GameObject[] objectToDisable;
[SerializeField] GameObject[] objectToEnable;[SerializeField] bool isCoroutine;
private IEnumerator coroutine;
public void Start()
{
if (isCoroutine == true)
{
StartCoroutine(coroutine);
}
}public void SimpleDisable()
{/*
if (objectToDisable.activeInHierarchy == true)
{
objectToDisable.SetActive(false);
}
else
{
objectToDisable.SetActive(true);
}*/foreach (GameObject obj in objectToDisable) { if (obj.activeInHierarchy == true) { obj.SetActive(false); } else { obj.SetActive(true); } }}
public void DisableAndEnable()
{
foreach (GameObject obj in objectToDisable)
{
obj.SetActive(false);
}foreach (GameObject obj in objectToEnable) { obj.SetActive(true); }}
private IEnumerator WaitAndDisable()
{
yield return new WaitForSeconds(2);foreach (GameObject obj in objectToDisable) { obj.SetActive(false); } foreach (GameObject obj in objectToEnable) { obj.SetActive(true); }}
} ```)
oh god
okay i'm only making it worse sorry ._.
i just finished learning vector3 and raycasting what should i do now?
whatever you want to
StartCoroutine(coroutine); how would this work? coroutine is never initialized.
sharing the issue you have would be really helpful to pinpoint the cause btw
Sorry it's getting late, my brain isn't braining anymore.
I think I'm just too tired cuz I can't even realise what I'm doing wrong
is
private IEnumerator coroutine
and
private Coroutine coroutine
the same?
No
There are a couple circumstances where they can be used interchangeably in the Unity API but they're not the same
Namely for StopCoroutine and when yield returning them
So which one should be preferred?
I'm used to writing private Coroutine coroutine
but here I saw private IEnumerator Coroutine so I'm confused now
if you're only using them for those apis where you can use either, imo it doesn't really matter, just be consistent
i tend to use Coroutine since it's unambiguous as to what it's for
What would be the difference in behavior then?
What does IEnumerator even mean
Like Coroutine reads nicely
you make a new temporary thread from my understanding
(not a thread, really. just something to check back on every frame)
IEnumerator is just something that can provide multiple other values
in the case of a coroutine, it's being used to provide YieldInstructions
Okay
So it's more readable if I use
coroutine = StartCoroutine(myRoutineFunc())
rather than
myIEnum = myRoutineFunc()
?
well those 2 don't do the same thing
consider these:
coroutine = StartCoroutine(Routine());
// VS
StartCoroutine(coroutine = Routine());
// or
coroutine = Routine();
StartCoroutine(coroutine);
just finished junior programmer what should i do now
Make game
im bad at coding
Make game, get better at coding
cant make game
