#💻┃code-beginner
1 messages · Page 403 of 1
So then why did you say that you had no instances
borderController is the name of a field. Are you talking about that field?
theres 2 scripts
implicit conversion is amazing i can use one type for everything
borderController and transitionController
I want to pass the lives value from borderController into transitionController
because I have this
Cool have fun I'm sure that's not going to backfire in a hilariously over-the-top fashion
borderController is not "A script"
just kicking a problem down the road to become a future you problem
yea its a class
borderController is a field -- a variable -- on your TransitionController class
Which instance of BorderController do you want your variable borderController to hold
Its type is BorderController
okay wait its clicking a bit
public Foo bar;
I have to actually put a Foo in this field, or else it's just going to be null
fields and variables that are not primitive types or structs are just a slot you can plug a isntance of that thing into
okay so I would type public borderController collisionCollider;
No, because there is no such thing as borderController
BorderController certainly exists
A field declaration needs a type -- the kind of thing it holds -- and a name -- how you'll refer to that field
The name can be whatever you want
public BorderController florp;
This would be perfectly legal.
okay I think I fixed it
public bordercontorller florp;
This would be a compile error, because there is no such thing as bordercontroller
okay well I got the same error in unity but VScode doesnt
Allow me to explain classes and variables using "The Cat Metaphor".
Imagine you are a mad scientist with a cloning machine. You can 3D Print any animal by running their genome sequence through your Animalizer 3000™️. You have the full DNA sequence of a cat on a big sheet of paper. This sheet of paper is not a cat. It is, in essence, how to cat. You cannot feed the paper catnip. You cannot flip the paper over and pet its belly until it bites you. It's a piece of paper.
Now, when you run that paper through the Animalizer 3000™️, you can make a cat out of it. The window pops open and you've got a black cat, and you give it the name ollie. you now have a variable of type Cat that is named ollie. public Cat ollie. This is an instance of Cat. This one can eat catnip and get belly rubs, but you can't fit it in the paper slot of your Animalizer 3000™️. It is not a genome, it's a Cat. It is no longer a script, this Cat is a Cat.
You can then feed that sheet of paper into the machine again, and the door pops open, this time, a gray cat. You can name him junior. If you want to call ollie, you'd use his name. If you wanted to call junior, you'd use his name. If your friend came to your house and you told him "Watch out my cat bites", they would probably ask you "Which one?". You'd need to tell him which cat is the one that bites. He could then store that in his brain as public Cat thatOneThatBites. Now, public Cat ollie and public Cat thatOneThatBites both refer to the first black cat, but each person has their own variable that holds it.
If you then told your friend "Watch out, because my Tapir also bites." they'd probably be confused. You don't have a Tapir. You have two Cats. There's no Tapirs in this house! Why would they tell you the Tapir bites if there is none? They are confused and angry. They start smashing stuff in frustration. This is a NullReferenceException. Their variable public Tapir thatTapirThatBites contains no Tapirs because there aren't any. If you want them to know that there is a Tapir that bites, you'd need to actually have a Tapir to tell them about.
Now, your file, BorderController.cs is the genome of your script. Have you ever "turned on the machine" by attaching that script to an object anywhere?
also this is genius someone please pin it
i now perfectly understand
can anyone help with a player movment issue
Why private? Better chance of getting help if you ask here
I was originally going to make this a youtube video but I can't draw and can't be arsed to have someone draw it for me
Reflection is when you shove the cat back into the machine
allowing you to pirate your cat by creating new cats based on its reverse-engineered blueprint
Reflection is when you hand someone a big box with a ? on it and telling them that whatever is in here, you can definitely pet it
that sounds more like an interface
Here's my pet System.Object
Yeah, fair
actually, that is a very accurate description of one, haha
also about the above, anyone new should just forget what reflection is and never use it till you are experienced
actually reflection is COOL and we're just gatekeeping you from it because it's so fun and epic
okay well

hides the cat
pulls out reflection
finds the cat forcibly
pets the cat that you shouldn't be able to pet
has anyone done a "click on specific gameobject" event?
I have something I know I can make
but just writing the code feels daunting
okay so problem
its pretty easy to do, with the IPointerClickHandler and a physics raycaster on your camera
when I press space it does the transition but NOT when collisionCounter is 4
"My cat is in a box you can't pet it"
* Fires orange portal on wall *
Cool
Could you show me ropes?
2d or 3d game?
3d
Show the current code
this is my cat. he has IBS. you can't feed him, only i can
portals into stomach
ibs activates
but honestly i use orthographic camera
it's just that the z values will be different for reasons
ok better question does the object have a 2d or 3d collider on it
3d
so make sure you got a PhysicsRaycaster component on your camera
Got it
Done
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.IPointerClickHandler.OnPointerClick.html
then make a script like this
Okay, so you want to start the transition either when you hit space, or when the collisionCounting's collisionCount is 4?
when its 4
where it implements the IPointerClickHandler interface
when i press start from my main menu i cant look or move
the space thing is for another scene
and does the logic you wnat to happen in the OnPointClick method, then put this component on the object you want to respond to clicks
Both conditions call the same function
If either condition is true, it runs that function
Ok, done!
bcs im saying when its 4 it doesnt do it
Okay. What should let you look and move?
Try logging that value before you check it
yeah so that OnPointerClick method, will execute anytime you click a object that has a collider that you put this script on
theres also this
also make sure your scene has a EventSystem
unassigned reference erroir
im on first person template then added main menu, it worked at first but i cant remember when it didn't
Cool!
Any errors in the console after you press start from the main menu?
I assume that loads a new scene?
yes
Then all I have to do is call the object's TargetType.HandleBeingClicked()
So assign it
And implement a HandleBeingClicked() for eevery object
Thank you very much, @shell sorrel !
wait do you only want to act when a certian object is clicked, or you just want to always act but know which object?
I just want to select each object that is from a certain type
i took the obect called transStart off Trans Start just before to test
way i showed you is most ideal if you want logic to run on 1 object when its clicked, if you want it for any object without having to add a script to each one there are other ways. Like getting your mouses position then using ScreenPointToRay on the camera then using the returned ray to raycast
so something like
public abstract ClickHandler : MonoBehaviour, IPointerClickHandler
{
public bool CheckIfClicked();
}
Should do what I want just cleanly 😄
I see
It's cause what I want to do is complex
public void OnPointerClick(PointerEventData pointerEventData)
is what you need for the signature
not CheckIfClicked
Oh, I see
Also missing class
I want to be able to initiate a click event, also
So the next click is gonna determine the outcome of the event
seems like you're just recreating the EventTrigger component, but worse
IF it hits a target object type, then it returns that target Object type sas the target
else, it stops the event and doesnt do anything
is this in the correct order, if im trying to make a script to make text pop up when the mouse hovers over the cube
@remote osprey also if you dont want to call logic in this script like @slender nymph suggested, the EventTrigger component will letyou call a function on a other object when this object is clicked
Oh is see
a cube is not a UI object, it should not be attached to the canvas
i thought the cube should be the child of the canvas
How do i do this exactly? xD
Add Component -> EventTrigger
man idk what to do
the children of a Canvas object should be UI objects. a Mesh Renderer is not UI
then in there you can listen for multiple types of events to execute a function on, works smilar to how Button does in UI
so should the canvas be a child of the cube?
if it is not a world space canvas, then no. if it is a world space canvas, then sure. but does it need to be a world space canvas
oops
I put a mesh inside my canvas xD
Then inside the mesh there are UI gameObjects
It was working fine, tho :p
What is the problem currently
but if i go to my firstpersonmap without the main menu it works fine
Cool!
I'll try it out
i don't know what "your purpose" actually is.
when canvas needs a position in the world
im not tryna make it have a position in the world, im tryna make the text appear on the screen
wait i can fix the bottom one
The variable transStart of TransitionController has not been assigned. You probably need to assign the transStart variable of the TransitionController script in the inspector.
Looks like the variable transStart of TransitionController has not been assigned. You probably need to assign the transStart variable of the TransitionController script in the inspector.
So then it looks like this Cat isn't the one that bites
okay then I should assign it
You should try to find the one that doesn't have that field assigned
Hint: you can search your hierarchy for instances of a script by typing t: Script Name in the search bar
Isn't that... Unreal Engine?
GET HIM
I typed t: TransManager and it didnt work
wait wrong worfd
@polar acorn i literally cannot find where it isnt assigned
Have you searched for every TransitionController in your scene?
put a log on the line right before the error that prints the object it is null on
search doesnt work
Is your class named Transition Controller?
That doesn't say Transition Controller
oh
ill do that
Show your search results
no, but also why do you have the same code in two scripts
i just realized yea ikd
that's not even the same code
Show the search results
now show the TransitionController component on each of those two objects
Hey look there's two of them
found it, but now I get a COMPLETELY different error
Do they all have the variable set
!docs
Go ahead and just clear that
found something weird too
If the stack trace doesn't mention a script you wrote, clear and see if it goes away
this object didnt exist until now
and I cant put anything in the collision counting
You can probably put a BorderControl instance in it.
!vscode
There's no such thing as "temporary objects" unless you've explicitly coded it to do so
i didnt make a temp object and it still made one
yea the error is from the temp variable what the hell can I do @polar acorn
What is "the temp variable"
for that matter, what is the error
lemme sss it
it makes an object called "transition" and THATS where this error comes from
I cant put the script in the slot its supposed to
What makes that object?
cs:25 means the reference in that line is lost.
i dont want to delete it right?
So, where do you assign collisionCounting?
And did you check to make sure you don't have another copy of TransitionController?
And is it on any other objects
Two questions:
- do either of them have a variable missing
- why is there another instance of this script on another object
is there a way to force framerate other than Application.targetframerate
Should there be two? If so, you need to assign the variable on both
ill disable it on border
Why is it on border
is it supposed to be there
Why do you need something else?
idk i was jsut wondering if it was like a quality option or something
cus idk how i would set it to 60 right as the application started
From Awake in a script in your first scene
@polar acorn yea the error is this temporary object that goes away when it iisnt running
is it the coroutine?
IT IS
how do I set the collisionCounting in here now
YUP
still not working
startcoroutine() is the only way to call another method within a method?
No, that starts a coroutine
no?
Or what exactly do you mean with "method within a method"?
@swift crag might just have to force 60fps on the game which is annoying cus i wanted it to be smoother, but most dont have a monitor above that value anyway so
So then you're spawning it somewhere
If you don't want to spawn it, don't
is it the coroutine?
¯_(ツ)_/¯
You wrote the code, where are you spawning an object that has this script on it
I haven't followed this thing all the way but are you doing your logic in FixedUpdate, Update or both?
but it makes an object ive never made
Objects don't just spontaneously come into being
You're making one somewhere
either with Instantiate or new GameObject
originally some of it was in update, but i've sinced moved all of it fixedupdate. im trying to get a replay system working, but some discrepancies keep creeping through and desyncing the players, and the only thing i can think of at this point is that the framerate is really high
You cannot assign an object in one scene to an object that is not in that scene
whether it be a prefab or in a different scene
okay well
now im in the other scene
i cant put ANYTHING into collision counting
okay well now theres an even BIGGER PROBLEM
THE SCORE KEEPS STAYING AND WONT RESET WHEN YOU RESTART THE GAME SCENE
im dealing with the transition stuff later
this is more pressing
If you have any logic in Update (or other framerate-dependent logic) then even limiting the framerate wouldn't make it deterministic.
It doesn't assure that the framerate stays exactly at the max value. Like a target of 60 could bounce between 59 and 60 as far as I know (assuming that your PC can run it 60+ fps)
guys I seriously need help
this is a core part of my game
I cant have this be messed up
i need the score to reset every time the player enters a scene
lemme do some resarcg
I've literally searched through my entire project, and couldnt find anything using update() relevant to the fight simulation 😭
Isn't your score manager a singleton?
idk
Just have something in the new scene reset it on Start or something
okay how do I do that
You remember how you accessed the score to display it
Do that, but set it to 0 instead
so in start I just do
0 idea why this is happening, just copied the code from another one of my games
i am on a slightly newer version of unity so maybe that's why?
The version has nothing to do with broken code. You don't have a GameManager class according to this error.
Not how you accessed the text, the score
please help me with this, i dont know what to do here
You'd assign it the score value as a string from the instance of the score manager.
Do you remember how you accessed score when you were trying to set the text
scoreManager
No, in this case they want to actually change the number
so then I should put start in there right
If you want it to reset in a new scene, put it in Start on that scene
thanks 👍
Start runs on the first frame an object exists for. If it's on any object in a scene, it'll run when that scene loads
I'm convinced this system I've made is vulnerable to even a sneeze and it all topples over
Because why does a replay work flawlessly one time and fail the next time
Would frame dips mess anything up?
Debug it to figure it out.
It must be some RNG function, or framerate... those would be the only two variables right?
!vscode
Surely, lol. Back on that grind tommorow 💪
I've been keeping recordings of the game state which has player locations and velocities. They are very similar mostly, and sometimes identical, but most of the time they're off by about a tenth of a unit, which could be the problem.
I thought you fixed this already?
#💻┃code-beginner message
different issue
If by resetting it you mean setting it to 0 when start runs, then sure.
Have you tried it? Because this is extremely easy to just run and see what it does
i mean when you re enter the scene
Ok, and what happened when you tried?
I assume that by "it" you mean the score, and "keeps being added" you mean from the value it was before the scene reset.
Is scoreManager in DontDestroyOnLoad? If so, Start will not run
oh shoot
Please try to be a bit more descriptive too. Because that was very confusing
lemme get rid of this right?
If it is in DDOL, then you can do a few things
Either register to the onSceneChanged event, or just set it to 0 where you load the scene
No
ok
lemme look into that
You might already know this but Application.targetFramerate might help
I cannot for the life of me understand why this does not work when the queue is larger than 2: public void ClearFormationQueue() { for (int index = 0; index < nextPosition.Count; index++) { GameObject destroyMe = nextPosition.Dequeue(); Destroy(destroyMe); } Debug.Log($"position queue cleared, new size is {nextPosition.Count}"); }
while (nextPosition.Count > 0) {
GameObject destroyMe = nextPosition.Dequeue();
Destroy(destroyMe);
}```
your code doesn't make sense. Think about this example with 5 elements in it:
index count
0 5
1 4
2 3
3 2 << your code will stop with 2 left.```
Hmm y'know that makes a lot of sense
I guess a for loop would never work for clearing a queue then?
if you really wanted to use a for loop it should look this way:
int count = nextPosition.Count;
for (int i = 0; i < count; i++) {
GameObject destroyMe = nextPosition.Dequeue();
Destroy(destroyMe);
}```
just reading the count once at the start
can I still have some help with this?
im very confused
Damn. '.Count' being different every pass through the for loop never occurred to me. Thanks!
You call LoadScene somewhere, right?
Just set score to 0 right then
Why not?
i cant find it
like check this out
wait
should I just make a new script
I FIXED IT
YEAA
nvm
i didng
Can you stop spamming?
okay im sorry
And stop bothering people, if they want to take a break from doing this dance again, let them.
okay, im sorry
dance he said lol
No, you should not make a new script.
You should absolutely know where you have the LoadScene call. If you don't, ctrl+f it like in any text program or in a browser
wait i think I found it out. I put the line of code when the scene changes to the leaderboard, not when the leaderboard changes to the gamae
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It's definitely the problem. Butterfly effect.
Even if you record them perfectly, there's gonna be an error due to floating point error. Saving positions and velocities is very unreliable. Instead you should be saving the inputs.
And be running the same logic during a replay as during an actual game, but providing inputs from your replay data instead of the player controller
That's how some AAA fighting games handle replays
Hello, I am a beginner at c#/unity. Can somebody tell me how I should create a building/hammering animation. Should I use code to transform the object or should I make an animation?
Either way would work. It's up to you and your game design choice.
Which way would be easier if I will use the animation very often?
Easier in terms of what?
Implementation?
Yes
Well, depends on how sophisticated you need it to be. If it's just a building rising from the ground like some strategy games do, it would probably be easier to just code it.
If you want a unique animation for each building with walls and other parts rising and what not, it's gonna be pretty difficult to do via code.
OK, thanks
What is the preferred setup for C# code editing on mac with unity
is it vs code? or visual studio for mac? because i've heard bad things about visual studio for mac
I use Rider
i've never even heard of that
ok, i'll check it out!
Visual studio for mac is essentially just visual studio code from what I understand.
i just got started with vscode for mac and found it straightforward
added a property and it compiled when i went back to unity. very similar to godot
yea the Visual Studio mac is getting retired and fully replaced with VScode @potent raft
neither hatebin or hastebin are working. Any other alternatives recommanded?
there are several alternatives linked in #854851968446365696
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't know if this is more suited for #archived-code-general, but I have a big problem here and need the function to have a very precise functionality.
Function -> https://gdl.space/nucilatawi.cs
Fragments are parts of Pieces. At some point in the code, a Piece will call the function on each Fragment it consists of twice. Once with Vector2(0f, 1f) passed, once with Vector2(1f, 0f), so, vertical and horizontal.
The function is supposed to check both ways if the fragment exists in a position where it's in a horizontal or vertical line between two Walls, with at least one Fragment (including itself) and at least one BrittleWall with it inside the line. If yes, set itself and everything between these two Walls as marked. Later on, marked objects will be deleted. If there is air or anything unwanted detected, the function automatically fails. So no air or players.
There is a problem with this, where stuff just isn't properly recognized. In the formation on the screenshot, selected Fragment(1) is somehow telling me that it encountered a wall, when there is no wall it could access.
If anyone has any idea on how to fix this, I'd greatly appreciate it.
I think it's working
but I'm not sure
would netcode for entities or something like Mirror be better for a base building strategy game with multiple worlds
you also need to research the available networking solutions to find out which fits your needs best. there is never a "one size fits all" answer to something like that
what is a good way to break of out update loops?
can you be more specific about what you mean by that
huh? it's a unity method. it runs every frame . . .
im not sure if this is the correct way to do it
i want to activate the function A when isDone is true
what is function A? and what isn't working?
i just wanted to know if there are other methods of breaking out of update loops
my animation wont work in one scene but it works in every other scene 😭
this is rlly strange
you can put an early return at most, there is no "breaking out "
oh alr thx
Update is not a loop. it is a regular method that just happens to be called every frame. the only time Update is not called is when the component is disabled or the object it is attached to is inactive
ah i guess i misunderstood its function, thanks a lot
your ide doesn't appear to be configured correctly
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
why do you think that? we can clearly see that the Update method is recognized as a Unity Message. that indicates that it is in fact configured
LOL I was playing an old game that changed my moniter colors
all the text appeared white 😭
okay so for some reason I have an animation that plays in EVERY other scene BUT this one
i think its a code thing
you really ought to give #854851968446365696 a read at some point
isnt this a help channel
i'm guessing you didn't bother actually reading the channel i suggested you read
You might want to provide the necessary data like code, what you've tried, what's happening and not happening, etc
please finish a thought before pressing enter again
so I have scripts in other scenes that have an animation play when a button is pressed, however, in the actual scene of the game, I have it configured to play the animation when an object collides with another object 10 times
lemme send my code
!collab 👇
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
my bad bro
Maybe verify the collision count
the scene still changes when it collides 10 times though
the animation just doesnt plau
So the coroutines fires and code works?
So this isn't a code question but rather an animation setup problem?
seems like it
Could try #🏃┃animation or #💻┃unity-talk
Make sure to provide the necessary like animator controller and whatnot
Not really. Technically there is return; but your code just runs next frame
Best thing is a state variable that determines how far it is and to see if it should run from there
Consider putting your code in a separate method and then write a check as a guard clause
so it's not in the way of anything else using the Update method
Hi! How can I add a collaborator to my unity project on the free plan? (we're both on the free plan and I've watched tuts but nothing actually tells me how?) Sorry if this is the wrong place to ask! I hope it isnt haha I thought it would be the right place since I'm a newbie coder trying to collaborate with another newbie coder
!vc
probably better another channel, maybe#💻┃unity-talk or #archived-unity-gaming-services
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
thank youuu I really appreciate it
git is also pretty much the best option if you arent so deep into learning unitys vc. Used in every other aspect of computer science as well
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
this code doesnt work right anyone knows how to fix this?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
For the last 5 hours of my life I've been trying to fix this one script from freaking out randomly. I tried so many changes I don't even remember what I was doing, but every FIX resulted in another BREAK. Something is always broken. This is the state at which I noticed the error. Tell me what to fix here, PLEASE. The script is supposed to mark the fragment and any line of brittleWalls and Fragments including it on any axis between two Walls with nothing else inbetween. These would then break, which you can see working in the video above, EXCEPT THIS ONE CIRCUMSTANCE which rips horizontally. I don't know what's causing this shit to freak out this bad, but I'd be eternally thankful if anyone manages to tell me what will fix this function.
It used to be a very clean, short piece of code, but now it's a screen sized mess of useless crap I tried to use as band-aids just to be done with this.
I'll stay here until someone maybe asks a followup, which I'll do my best answering and guiding
Function --> https://gdl.space/izalohejim.cs
I don't want to give up on this project because of a little shit like this
I suspect it's with the order of checking stuff
but I can't think anymore
my brain's a soup after all the attempts at fixing this
I'd even go in a call and stream all the scripts to test whatever you need but there's no vc here
I'm not on an appropriate device to be debugging based on videos but I'm assuming the issue is with the last detection where it had destroyed two separate segments from that three piece (4x4).
Although you're able to visually inspect what's wrong, log those pieces and verify why the first portion of your code added them to the list to be marked for destruction. According to the code, hit count was greater than 2, fragment count was greater than 0 and brittle was above 0 - obviously we're in disagreement with what had occurred so we'll need to figure out which of these were wrongfully added.
btw no need to worry about when this occurs. All marking functions are executed on all pieces, on all fragments, all at once before proceeding with destroying the marked ones
also pieces move, not fragments, so it's not like the function was run before the rest moved
what do you need to know/confirm from me?
we'll try to do this
if you want ofc
As a last resort I could just rewrite the function from scratch
I'm assuming this line was true when it wasn't meant to be
if (hitWalls >= 2 && hitFragments.Count > 0 && hitBrittleWalls.Count > 0)```
I think yes
unsure how to confirm that
obviously it runs
as we see
but if that was the case, why did it shift over 1 full length
Whenever I switch to Android/Windows and create a build I suddenly have changes in these files.
I wonder if I should commit these changes?
Oh I also have changes in sln.DotSettings
You'd first just log the hit fragments and brittle wall elements to see which pieces were found. Then go in reverse and figure out why they were added to the lists.
So which pieces were in the lists?
the ones deleted. The walls above the top fragment and ones below the right fragment, including the fragments
So everything that's in the lists, including the fragment executing the marking will be deleted as stated in this area
So you'd want to validate each of the three expressions:
- what was the actual number of walls hit?
- which part of the code added the fragment elements for this specific case?
- which part of the code added the brittle elements for this specific case?
we can add a counter that increases every time I add something to the lists
Just printing the number of hit walls would be a start
you mean the ones stuff should be between?
I'd like to know what the hit walls value was before the unwanted behavior
if it was more than 2 it'd say "between 3 walls"
it's logged right here, just before marking everything in both lists including the fragment itself.
I cannot see the logs from the video but that's good to know - mobile device portrait mode resolution.
the values are correct. That part works as desired, it's the actual detection messing up
Now which of the if statements between lines 27 to 75 added the objects?
You can probably verify this by adding some unique statement prior to adding to the lists
At this point I think even if we fix this issue the function will be cluttered as hell. I might as well just rewrite it to save us time.
Figure out which statements are misfiring.
btw I'm doing this rn
tho it's weird it only happens in this exact scenario. For example when I did this (screenshot), it just stayed like that
there is some obscure shit happening. I really need to rewrite this
Thanks for help anyway mate
I think if I think and ponder a bit I'll get it right
after this mechanic an even worse one needs to be added
can i use implicit conversion for predefined classes too?
this code crashes unity, and i have no idea why. if someone smart could explain why it crashes, and how would i make it do the thing it's supossed to? (move the platform with the boxcollider2d, platform on the screenshot, and code snippet below)
using System.Collections.Generic;
using UnityEngine;
public class movetheplatform : MonoBehaviour
{
private BoxCollider2D BoxCollider;
// Start is called before the first frame update
void Start()
{
BoxCollider = GetComponent<BoxCollider2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector3 newPosition = BoxCollider.transform.position;
if (collision.gameObject.layer == 6)
{
while(newPosition.x < 3)
Invoke("TheMovement", 2);
}
}
private void TheMovement()
{
Vector3 newPosition = BoxCollider.transform.position;
newPosition.x += 0.5f;
BoxCollider.transform.position = newPosition;
}
}
layer 6 is the layer called "player", and the player gameobject is set to it, the BoxCollider is the box collider 2d of the platform
Hi everyone! New to coding and gamedev!
Any beginner for C# recommendations would be highly appreciated! 🙂
Check the pins. !learn may seem boring but thoroughly explains everything - skip steps if necessary.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
It's a good means for getting familiar with Unity, how to approach the api and whatnot - you'll not be making cool special stuff but it goes through the basics and will not mislead you (it's the official source to learn from).
i LOVE unity learn, rlly a great resource
Anyone know how the brawhalle attack system works?
first of all, what's the error Unity is giving you?
second, try renaming the BoxCollider variable to just boxCollider
it might be clashing with the class
what did i do wrong? ;-;
what does the error say?
you have to read the error
You are trying to reference the class itself. You already have a variable created, still, it will throw an error anyway.
move the cursor to read what the error actually says . . .
this will still not work
and you can't use it in the variable definition
it just crashes. nothing else, no error, no anything. the moment i click the play button it just dies
oh
it needs to be on start
read the error message.
ok
you can't just see a red squiggle and immediately shut down
firstly try renaming the variable
To do it this way, you have to either make your clip constant, or reference it in the method like Awake, Start, OnEnable etc.
Note that the 1st option does not make any sense.
and I believe you might have an infinite loop
thanks
as there is no delay in the while, it'll keep invoking thousands of times until it just crashes
(I believe)
Unity freezes when that happens
Yeah, if you mean there is no WaitForSeconds in the loop, Unity is just going to execute the code non-stop until it freezes
btw, that movement code looks very strange
Sure, because Invoke is called in a while loop while newPosition.x is smaller than 3
Since Vector2 is a struct, which, unlike a class, is a value-type, the once assigned value on this line is not going to be updated when changing the position of your BoxCollider
Vector3 newPosition = BoxCollider.transform.position;
The first thing you're going to do is reference the BoxCollider.transform.position.
You can save is as a class Transform, which is a reference-type, but not as a struct Vector3
Secondly, this is still going to freeze your Unity for at least 2 seconds until the position is assigned
Does anyone know why my headers aren't showing up?
[Header("Positioning")]
public Vector3 originalPos;
public Vector3 zoomPos;
[Header("Stats")]
[SerializeField] private float fireRate = 0.5f;
[SerializeField] private int damage;
private float nextTimeToFire = 0f;
[Header("Graphics")]
[SerializeField] private AudioClip shotSound;
[SerializeField] private GameObject decalPrefab;
[SerializeField] private Animator _animator;
Nope
do you have errors? is the file saved?
also ensure that you've saved the file, yes
It's saved with no errors
Yup, i added a new varible to the weapon and still no headers
[SerializeField] private float gluff;
Do you have the debug option enabled at the top of the inspector?
Where do i find that?
click the More Items (⋮) button to open the context menu, and select Debug/Normal
Where are you expecting them to show up
show screenshoits
Dividing each category where they were placed
You either:
- Have a compile error
- Have a custom editor for this script
or:
- You didn't save your code
Or you're editing the wrong script
Well because the new varible was added in the inspector, that rules out everything besides a custom editor
Did you check for debug mode yet?
I don't know how much debug mode lists
where is the new variable?
I know it does remove headers
Yeah not in dbug
Alright
Seeing a screenshot of your whoole console window would be great
for my peace of mind
[Header("Positioning")]
//New varible
[SerializeField] private float gluff;
public Vector3 originalPos;
public Vector3 zoomPos;
[Header("Stats")]
[SerializeField] private float fireRate = 0.5f;
[SerializeField] private int damage;
private float nextTimeToFire = 0f;
[Header("Graphics")]
[SerializeField] private AudioClip shotSound;
[SerializeField] private GameObject decalPrefab;
[SerializeField] private Animator _animator;
I meant in the screenshot
strange
Can you show the full script?
I see you're using FishNet
Maybe FishNet messes with things especially if this is a network component
What's that quick pastebin people use here? i forgot the name
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Does something happen if you add an order to the header?
[Header("Foo", order=5)]
Just shooting in the dark here, I have no idea why it would not work
Type or namespace couldn't be found
I would guess it's otherwise somehow a custom editor interfering
It does.
It has a custom editor
I remember this coming up before.
Yeah I'm thinking this is a FishNet problem
IIRC it has a custom editor for Component?
big if true
oof
what's this mean?
FishNet draws a custom editor for every single kind of unity object
If it doesn't respect the HeaderAttribute, then headers won't work
Perhaps someone should open an issue about it
I don't see anything on the github repo
That's annoying, but sounds like we found the root of the problem
I'll ask in their server about it. Thanks!
Yeah your exact code produces this in my project btw
so definitely fishnet
apparently the loop label is wrong.
pretty sure C#'s break doesn't work like that
need the full function?
you have to break out the epic gamer goto to jump to a label
so break goto rayCheck or something
^ that but the label should be in the place you want to go TO not before the loop
but really... avoid goto and labels if at all possible
so how do I break out of both loops from inside the nested one
can you show the full code in question?
the simple answer though is - put whatever you want to break out of in a function, and return; from the function
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
here
I need to break out of the loop, not the function
the loop is inside a function
out of the second for, check if mishap is true and break
but yeah that's possible too
one sec
why not just this:
for (int i = 0; i < 2 && !mishap; i++) {```
in the outer loop
that solves it all, no?
like ```csharp
for (...) {
...
for (...) {
...
mishap = true;
break;
}
if (mishap)
break;
}
not really
why not
I need both iterations, just a cancel last second
there's some code ran after the for
I'll give it a go
#💻┃code-beginner message this code will still run the stuff after the for loop
so just remove breaks and add the extra condition?
it doesn't affect anything outside the loop
well you still want breaks in the inner loop, no?
but I need the breaks to not run the rest of the loop
actually a if (mishap) { break } below the first if could just do the job
I'm saying leave this exact code, change break break; to regular break; and add this:
#💻┃code-beginner message
but really just putting this loop in a function would be so much cleaner
and using return;
you could even make it a local function and then you don't need to worry about passing local variables as parameters etc..
Any idea why this coroutine isn't working?
public IEnumerator StartOccupiedSequence()
{
float occupiedTime = UnityEngine.Random.Range(minRoomOccupiedTime, maxRoomOccupiedTime + 1);
Debug.Log("Will Wait for " + occupiedTime + " secs");
yield return new WaitForSeconds(occupiedTime);
Debug.Log("Done waiting!");
SetRoomState(RoomState.NeedsCleaning);
}
I am starting the coroutine in another script like this: StartCoroutine(room.StartOccupiedSequence()); but for some reason, I get the first Debug "Will wait for X Secs" then nothing happens.
Do you deactivate the game object of the component you started the coroutine from?
e.g.
StartCoroutine(...);
gameObject.SetActive(false);
is the GameObject the coroutine running on destroyed at any time?
Did you destroy the object?
The object that is running the coroutine was deactivated or destroyed
OR
Time.timeScale is 0 or small
The object that started the Coroutine is destroyed yeah.
then mystery solved
Time.timeScale is never 0
it's gooooone
ohh, so it isn't supposed to be destroyed?
StartCoroutine doesn't mean "run the coroutine out in the aether"
it's equivalent to this.StartCoroutine
you run the coroutine on a specific MonoBehaviour
whether it should be destroyed is up to you but it's certainly not going to continue to run its coroutines if it is
if the GameObject is destroyed, the coroutine no longer exist; therefore, it cannot continue to run . . .
Ahh makes sense, I can destroy it after the coroutine then. Thanks!
you can run the coroutine on a separate MonoBehaviour class to avoid that, but may be more than needed for your situation . . .
I'm boutta snap bro
I rewrote the script, now it's clean, but the SAME THING HAPPENS
https://gdl.space/ivebedalin.cs
Everything works except this script. Something is just completely wrong here
Destroying the object after the coroutine worked perfectly, but that's a nice suggestion
@swift crag bro would you mind giving this a look?
I have an idea on why this is happening but I'm not sure
or anyone
over 7 hours and this is still giving me a headache
I find this very hard to parse.
there's extra info in the convo below when Dalphat was trying to help
The fact that you are being very emotional steers me away from helping you tbh
Put break points where you're adding to the lists and see which are misfiring.
ik
I'm sick today
my bad mate
It's not going to be a simple "you did this instead of this" solution without debugging.
I'd also be steered away tbh
yeah ik
Do you need me to add comments or send something external? Rvec3() just rounds all values of a vector3 argument passed
Basically the two lists are being populated when they aren't supposed to be because the if statements in your double for loop likely doesn't handle some edge cases.
Problem being I have no damn idea what the edge case could be, both brittlewalls and fragments are treated the same way.
whoa, this is a lot to look at and try to figure out what is going on or supposed to happen. is there a specific snippet/part of the code that doesn't work?
That's the problem, I tried figuring this out all day. As dalphat says, there appears to be an edge case where the objects break sideways
I can try the same level but replace the brittlewalls for fragments
just to get the possibility of treating them differently out of my head
ok here it didn't work because there needs to be at least one brittlewall and at least one fragment to break
This is likely true when it isn't supposed to be #💻┃code-beginner message
Specifically the two lists have added the blocks when the blocks shouldn't have been added - logic flaw.
The solution was to test and see which of these if statements were adding to the lists so he could further focus on the actual problem. As is, there hasn't been enough debugging yet.
My biggest question is why does it, like, shift to the side??
how does that even happen?
I think I could add a non-marker bool as a debugging thing and just check it on for the right fragment of the piece causing trouble
😭
private void OnEnable()
{
Application.logMessageReceived += ShowMessage;
Application.targetFrameRate = 60;
SendNotification(MessageType.Info, "GameManager Created, Set fps to 60");
why does it still say 165 fps
What's generating that text?
idk what we'll get out of this
it looks cool, but i'm unsure what the video is supposed to convey . . .
i dunno, i presume it's your code that's creating the text
this fps counter i found on unity forums
https://gist.github.com/st4rdog/80057b406bfd00f44c8ec8796a071a13
nothing, me admitting to a dumb mistake.
On the other hand, it's solely an issue of the top fragment of the piece.
I disabled the bottom right, changed nothing
Oh goodness, I don't want to read/debug/fix their code too, maybe someone else will help you out - apologies.
turned the nonMarker bool on for the top one and it works as intended now.
so something's up with the top fragment
lol thats fine, could it possibly be because of vsync, though?
I'm not sure as we'd need to know where or how that 165 fps is evaluated.
165 is the refresh rate of my monitor
which is why i thought that
turns out turning off vsync fixed it lol
i can definitely feel the difference now
Unity's trolling at this point
Can you explain the problem in a couple of sentences?
if you change the nonMarker bool does it work?
i didn't understand the intent or design or your game, so i couldn't what or where smth was wrong . . .
I'm trying to implement a mechanic where if 1+ fragments of a piece and 1+ brittle walls (grid things) are in a line which begins with a wall and ends with a wall and has no air and no other elements in it (I checked, the special floors don't break anything) the fragment and brittle walls in that line break, similar to tetris.
Here, as you can see, for some reason, this specific piece just breaks stuff diagonally.
I deleted it and placed a new piece of same exact shape, we'll see how that goes
wait
you're kidding
if you push a red piece with horizontal or vertical blocks touching opposite ends of this grid, they are all removed?
no, because at least one brittle wall needs to be in the line as wall
This is fully grid-based, correct?
If so, you should throw out the raycasting entirely and just work in grid-space
that would simplify your code quite a bit
anyways, turns out I did everything right from the start and wasted yall time, because this specific block was just built different.
I deleted the old one and placed a new one of exact same shape and position
now everything works as it should
I mean I should get used to stuff this tiny messing up my entire day, happened three times in this project already
sounds like a weird physics quirk caused by these raycasts on a grid (:
wouldn't the grid (brittle) column on the left break before pushing it to the right (where the second brittle column broke)?
btw, very cool game!
once was a misspell by capitalizing a letter on accident, another was assigning the Piece script instead of object to the room
Wouldn't it be cleaner to ditch the boxcolliders and raycasts and use a 2D array instead or something
I wouldn't use physics for such a game in the first place
What should I use then?
Yes it's pirely grid based
Just a grid
a grid
2d array
you can use Unity's Grid component
so comparisons like this.x == me.x + 1 >> move?
it converts between world-space and grid-space
Well you'd use Vector2Int or an equivalent for coordinates and yes just check things manually
It sounds like it's too late, but thank god this is just a test demo to see if people like the idea
Very simple for loops etc
in the actual project I'll ask some more questions on proper code stuff like the grid things.
Raycasts make sense when you have irregularly shaped objects spaced far apart
They do not make sense for very rigid grid-based logic
I mean I planned some off-grid mechanics, but that just sounds painful to work with so I scrapped the idea
The idea for it and most levels comes from the idea guy in my team, I just glue stuff they make together
I don't take credit for it
Thanks to you all for the help
but now I need to make them split into individual pieces if a cut occurs in the middle of a piece
I won't whine like I did today when I mess it up tho
cyall
cya all
however you say that
dude
well, a poorly coded game isn't a cool game, so I guess you have credit 🙂
nav I leave it to them
Can anyone help and tell me why this is not breaking?
Script -> https://gdl.space/jerovuxuwi.cs
the given script is inside each fragment and it's called vertically and horizontally (Vector2(0f, 1f) and Vector2(1f, 0f) passed as the lookDir) in a LateUpdate, after everything happens in terms movement and so on. It works literally everywhere except this piece. I tried deleting it and placing a new one, still not working
like this it works
Why isn't my tag changing when touching another gameobject https://pastecode.io/s/1n3ouidw
pushing the T piece in leaves a dot
Add this log to the first line:
Debug.Log($"Colliding with {other.gameObject.name} on layer {other.gameObject.layer}");
See what thing you're hitting and see if it matches any of your conditions
Might be a simple question and answer, but have you guys experienced switching a camera from base to overlay and back killing all values that have been there for physical camera for example?
mainCameraData.renderType = spectator ? CameraRenderType.Overlay : CameraRenderType.Base;
I added a Debug Log so
Okay, what does it say?
It says Ninja which is supposed to happen when the gameobject tag = other falling 2.
Using my exact log, what is the exact message you are getting
Guess I have to store it in an extra component to assign back when renderType base.
Alright I fixed it. I just forgot to add the fragment itself to the list. Again, I appreciate all the help and advice
I don't want to
Then perish
Ok
Why ask for help if you don't want it?
If you're not going to actually do what people ask of you, please stop posting here. You have been a difficult user in the past to attempt to help. Consider this an official warning.
i need a bit of help with an animation playing, and th problem is the code. I want it to play when the collisionCount is equal to 10, and when I put it in Start() it plays, but not when the value is 10
lemme send my code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Are you getting your debug logs?
on Start yea, on collisionCount no
Then this object never collides with any triggers
I have this graphic script that I found, but i've put it on canvas and im not getting the debug logs at the end.
public class UILineRenderer : Graphic
{
public List<Vector2> Points = new List<Vector2>();
public float lineThickness = 2f;
protected override void Awake()
{
base.Awake();
material = new Material(Shader.Find("UI/Default"));
}
protected override void Start()
{
base.Start();
Debug.Log("UILineRenderer Start");
SetVerticesDirty();
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
Debug.Log("OnPopulateMesh called");
the Start one is being called
but not OnPopuklateMesyh
The Three Commandments of OnTriggerEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 2D Rigidbody on at least one of them
well, the weird part is that it switches scenes when it reaches 10 but the animation doesnt play
i know it isnt a problem with the ACTUAL animation
bcs it works on other scenes
If you aren't getting your log message in OnTriggerEnter2D then that function simply is not happening
you need to have the rb?
I didn't know that
Sure
interesting
No I just made up a commandment for no reason to confuse people
One of the two does
no, that's not what I meant
It's not you were confusing people
it's just I didn't know
Either of them or both should have a Rigidbody
I only thought both had to have colliders and at least one of them had to be a trigger
Yeah, I was just snarkily replying because I put it in the commandments because it's a requirement
Sure
They do, that's the first commandment
Both should have their Colliders, and either or both a Rigidbody
at least one. They can both have rigidbodies just fine. My words were chosen very carefully
Wasn't there a rule for easy fast and free assets as well?
That's why I said "either or both", which means "at least one, can be two"
Oh, right, I missed the "or both", my bad
Now I have the reading comprehension shame cone 😔
well, I get the debug log
So then why did you specifically tell me otherwise
The method
OnTriggerEnter2Dis called when theCollider2Dwith the script that detects a collision is atrigger, otherwiseOnCollisionEnter2D, regardless of the otherCollider2D's type
So both can be non-triggers
shoot im sorry
Likely it's to do with your animator controller if the logs are printing
okay this may sound dumb but
if i copy the same controller
from another scene into this one, will that help?
Well, this will work
Not sure with what it should help, haven't followed
aaand still didnt work
Maybe show your animator controller
Referring to something like this
any simple ways to prevent randomly spawned enemies from spawning within each other
is a placeholder needed to see if they will collide, before placing
You can overlapsphere the area to check for collisions with other enemies and then doing that until you find an open spot.
Though you'll want to set a hard limit so you don't cause an infinite loop in situations where there might not be space. And just either cancel the spawning, or allow spawning wherever in those circumstances.
And what is the transition condition
Okay, that's all fine. I was suspecting Exit Time might have been enabled but this is all set up correctly.
Replace this log:
Debug.Log("Triggering the StartTransition animation.");
With this one, that gives a bit more info:
Debug.Log($"{gameObject.name} is Triggering the StartTransition animation on {transitionAnimator}", this);
will do
Also, quick sanity check: The birdTransition state does have an animation on it, right?
where would I find that
You'd click on it
like this?
ah
I think he's referring to the state from here
which node do I click
The bird transition state
Okay so it has a clip, that's good. Just wanted to make sure it wasn't an obvious problem. Back to the log then
ok
What’s especially weird is that
I literally copied tbe components
Should I just send screenshots of everything involved?
Let's start with just the results of that log
Please read #854851968446365696 on how to ask questions
This doesn't look like it's related to coding and a cross post from#💻┃unity-talk message
oh mb im new to unity
hello is EventTrigger.OnDrag called multiple times per frame?
Okay, so, the border object is changing the animation on the transStart object. Can you show the full inspectors of both objects?
Show the full inspectors of the objects, so I can get some context
That's good enough for border
I just needed to see the collision-y stuff since that's what's calling the function.
transStart next would be good
Okay, everything seems to be on the up-and-up. The only thing I can think is maybe the animation clip itself is incorrect?
The best way would be to just change that state to be the "entry" state and see if it plays when you start the game
kk
wouldnt putting it in Start() do the same thing? just curious
bcs i did that and it played
Okay, so the clip works. If it doesn't play then, maybe an object involved in this gets destroyed or deactivated? Or some variables change?
ykw it may be
okay no its not what I thought it was
i disabled an object that included the script that was redundant and it still didnt change the outcome
If it works in start but not in the physics callback function then it's likely not being called or something has happened later (outside of start)
When playing at the start method, are you firing the same instructions - changing scenes and whatnot
in Start() all I did was use StartTransition()
wait hold up
something changed
okay so
the image im using to transition is BEHIND the background image
yea its behind the image but its in the highest part of the canvas
Okay, so it is animating, it's just behind everything?
Canvases are drawn back to front in hierarchy order. So, transStart is rendered, then scoreText on top of it, and RawImage on top of that
OH
so its in reverse?
okay so it works, but now the transStart isnt on top of everything
Picture it as a physical drawing. Once you put something on paper, if you take a crayon to it after, it's going to end up in front of what's already on the paper
its just over the background
This order applies within the canvas. If you have another canvas, or objects in front of the entire canvas, they're still going to be in front
Where the canvas is in the hierarchy doesn't matter. The hierarchy determines order within the canvas
yea ik
wait lemme send a ss of what I mean
see how the small birds are above the big one?
Is the canvas an overlay canvas
Okay, so, then you'd need to make sure the distance between the camera and the canvas is less than the distance between the camera and the stuff in the game world
wait but if I make the canvas overlay, it makes everything huge
That's so it's in real pixel sizes. The position and size of an overlay canvas don't matter
but then I run the game and the other game objects are hidden
An overlay canvas is drawn directly onto your screen. It doesn't really have a meaningful position in the world.
So, that bigger box is your screen. That's the stuff that is drawn on top of the game. Imagine it like a sticker inside of your computer monitor. It does not matter where it is or how big it is, it will be your screen
It's drawn over everything else
Where are they on the canvas?
Or do you mean your non-UI stuff doesn't appear?
If it's the latter, that's probably because your canvas is covering them
Yeah, that's what your camera sees. And your canvas is glued to the inside of your screen
it literally does not matter where the canvas is
it can be anywhere
Yes, because it's an overlay canvas
it's covering everything
ykw
Overlays are drawn on top of the game
oh wait I see
so do I have to manually move everything
or can I just make the image smaller
its not its an image
your canvas should contain UI that is drawn on top of things
You don't. It should probably be either a sprite in world space, or a skybox texture
okay so ill make it a skybox texture
wait i can just use sorting layers
well
it works!1
Hey, I have an object in my hierarchy called "ScoreKeeper" and I can't reference to it in my code. For example if i try to declare the "ScoreKeeper scoreKeeper" it says that the type 'ScoreKeeper' can't be found. The object is enabled
In ScoreKeeper scorekeeper, ScoreKeeper is a C# type - it'd be referring to a class you've defined in a script, not a GameObject
And how should I refer to the game object "ScoreKeeper"