#💻┃code-beginner
1 messages · Page 5 of 1
Follow the steps linked above and don't skip anything even if you think you did it already
I'm not certain of your setup but here's an example: https://gdl.space/munegarivi.cs
Yay! i think its working now. I had some "issue" that other rays caused me. I only slept 4 hours in the passed 2 days so can't really think straight. Thank you for your time guys.
Guys, How should I display other language text?
You can watch a tutorial or read the docs https://docs.unity3d.com/Packages/com.unity.localization@0.2/manual/index.html
Whatever you can find on the net and that is easier for you. Tutorials and docs should be easy to find for Unity.
you need to use a font that supports those symbols
what font should I use?
It already supports in editor..
Any font you want that supports those symbols
whatever font you are using currently for the ui text does not support it
find one that does and use that
I have a float called "lifetime" which is for my battery % . I'm struggling to add it to this part of the script. I want my light to start flickering at 10% lifetime
What's this script?
If anything, you could evaluate life time in some update and have it modify the light intensity.
it's for my flashlight. I have made it so my flashlight flickers. just cant do it for it to only happen at 10%
Ah, okay. cs if life time > threshold return
You'd do this prior before any of the above. No point in doing anything if the condition isn't true.
so i can put all this into a bool and if true then this activates?
Umm I'm not sure what you're saying exactly but you'd simply not do the other stuff if the condition isn't met.
If anything, you might also want to reset the intensity before returning so that when the battery increases over the threshold, it resets.
light intensity = default
if battery > threshold
return
...
light intensity = flicker```Where you'd flicker if the threshold (low on battery) is met.
Can someone give me fpc controller or movement ?
"Unity fps controller"
You can also try the asset store and see if there are any free ones
Or paid ones.
alr il try thx
I might find tutorials on flickering scripts. I'm not sure what half the script means and I don't like that 
Thank you though
is this good?
It's free - give it a shot
Probably. 
alr
Sorry, I have one more question. Regarding custom methods. I've looked it up before and it didn't quite make sense to me. Why is the method custom and not for example put in the void Update?
- This organizes the code better. If you want to do other things in Update that aren't related to lights flickering, they are separated logically.
- You can now call LightsFlickering from other non Update places as well, if you need that.
What would the best method of doing a top down camera be? Should I just keep it attached to the player sprite?
Cinemachine is the answer to any and all camera questions basically
I mean I was thinking of just putting it in between the cursor and player
Consider doing some tutorials on cinemachine
idk what you mean by that exactly but whatever you want to do, it's best done with Cinemachine
I mean im just putting the main camera somewhere
It's powerful and you'll learn to appreciate it's features - future prospects of buttery smooth transitions (free) at the cost of learning.
Yes the best way to put the main camera somewhere is by using Cinemachine
ohhhhh. I get it. so by referencing the lightflicker method in the update itself. Now i can do whatever I want in the lightflicker method without having a ton of stuff all in the update method itself
Can I not just use transform to put it over the player?
you can do whatever you want. Your question was "what's the best method" and so I'm telling you.
Should probably be fine but you asked for the best 😅
I was kinda talking about the best in terms of something I can throw together in like 20 minutes but thank you anyways
i drag this to main camera?
You should have a prefab or something which is already set up
cinemachine is much faster to throw together than writing a custom script
it's a few clicks
that's the point
open it and drag the fps controller into the hierarchy/scene
i dont see it
where is that
Assets/EvolveGames/RealisticFPSController
Thank you @wintry quarry @ivory bobcat for your help. Managed to get my flickering effect when below 10% and works flawlessly while understanding all the code
Hey so i'm trying to plan out a unity project and was wondering if i could get some opinions on its feasibility.
I want to try and build a library/plug in for creating templates for spells so that you can quickly generate different basic spells and modify them.
I'd like to be able for it to support the D&D spell slot costs and Mana costs methods so you can choose which ones you'd like to use in whatever game.
I'm going to try and let you specify stuff like the spells name, its range and duration, effects from a set of presets, types of projectile behaviors for the user to choose from or create their own implementations as they need.
I just want to make a customizable structure that others could import and work with.
sounds like an asset. that'll be a lot of work to make it modular, let alone a ui/custom editor for the creation process of the spell/skill, but it's feasible . . .
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Hey, can someone help me with movement jitter on an FPS rigidbody setup? I've scoured the forums and can't seem to get anything to work. Everything is super smooth when just looking, or when just moving, but when I move and look at the same time, it becomes definitely NOT smooth.
Things I've tried:
-Messing with update vs. fixed update vs. late update.
-Interpolation on the rigidbody.
-Messing with Time.deltaTime in relation to the controller scripts.
Player Controller: https://gdl.space/ibuvamayak.cpp
Mouse Look Controller: https://gdl.space/vawiyevani.cs
thank you looking now
updating as we speak
still not working unfortunately
instead of setting transform.localRotation on whichever objecrt has the Rigidbody you shuold use Rigidbody.MoveRotation
Where does the text go?
I just changed font size from 26 to 27.
still no vector2 😦
still not configured correctly
any idea how?
!ide and follow ALL of the steps carefully
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
installed manually followed the entire link.
when this changes you know you've done it right
okay will have another look thorugh
Did you select the workload?
i get no option for that lol
Sure you do. Run the installer again
where are you looking?
It's often overlooked but you should be fine now if everything (the easier non missed parts) is done 👍
yeah i thought it was on visual program not installer lol
The other workloads aren't necessary and can reduce install time if you don't have them selected.
okay will have a look soon, gotta nip out so back in a hour hopefully refreshed
Thank you, that helped greatly...not sure it's perfect but a big improvement
golden rule, never mix transform or character controller movement or rotation with rigidbody
noted, I appreciate the lesson!
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Hey, how do you use the "FindChild" function but it gets many childs?
I can only get 1 with this
what FindChild method are you referring to? do you mean GetChild? because that gets a child at a specfic index. why would that return more than one child?
I wanna do something like
gameObject.transform.FindChild("body", "head")
But the Find Child function only works on 1 child
that's not FindChild, it's just Find. and much like GetChild it only gets a specific child. just call it for each one you want to get
I don't get what is going with this in the tetris game righ tnow
those last things are likely editor errors. but also you should always start diagnosing issues from the first error in your console not the last
try restarting editor
and see if it persists
ok
I'm trying to use the CompareTag function but it keeps returning a null exception error
you can create whatever you have the skills to create
that's unrelated to the CompareTag method. whatever you are calling it on is likely null
this should help you diagnose the issue https://unity.huh.how/programming/common-errors/runtime-exceptions/nullreferenceexception
does the compareTag function use mesh colliders to find it's target or no?
CompareTag has nothing to do with colliders. all it does is check whether an object has a specific tag
the only relation that CompareTag has to a collider is that Collider inherits from Component so it inherited the CompareTag method. the method does not care what kind of collider it is, it's only purpose is what i stated before
I fixed it.
I got a problem with the red and black tetrominos is that unlike from the rest when I turn them around they do not go into the walls but for the red and black ones they go into the walls when I turns around, how can I fix this?
typically if you need help with your code you should show the !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I don't think it was in the original, but what this technique is usually called is a wall kick, you either displace these blocks when you decide to rotate them near a wall, or just prevent the ability to rotate them.
Actually looking at it again, you don't seem to update the actual block coordinates for what they can occupy when you rotate them
then how do I fix it?
When you rotate your blocks, however you're storing the coordinates for each segment, it needs to be updated
I don't know how to update that
bool CheckIsValidPosition ()
{
foreach (Transform mino in transform)
{
Vector2 pos = FindObjectOfType<Game>().Round(mino.position);
if (FindObjectOfType<Game>().CheckIsInsideGrid(pos) == false)
{
return false;
}
if (FindObjectOfType<Game>().GetTransformAtGridPosition(pos) != null && FindObjectOfType<Game>().GetTransformAtGridPosition(pos).parent != transform)
{
return false;
}
}
return true;
}```
So here you're iterating through all the transforms on your game object and checking if it's inside of the grid
Not too sure from here, but some of the segments should be returning false, yet they are not.
In your Rotate method if it is not a valid position you are using -90 3 times. if it is valid you use 90 only twice
I presume you mean to Rotate, check if valid if not rotate back
Hello I am trying to make a questUI that tracks objectives i.e. items collected X/5 and I figured doing this in update is a worse idea than using an event action but im unfamiliar with them if I do
OnUpdated += UpdateObjectiveProgress;
How do I then reference my event action in another script? Is it just ClassName.OnUpdated?
The script with the event on it should be the one calling the function
Other scripts reference this script to subscribe to it
I think im with you so far so that means I need a reference in my other script to the script to invoke the event?
Essentially, the thing with the event needs to know when to invoke the event but doesn't care to reference the things that actually use it.
The other scripts need to reference the event-caller to subscribe to it but don't care about the thing that triggers the event
Turns it to A -> B -> C instead of a web where all three things need to know about each other
Ahh I understand you thankyou, so I need a reference in the script that is invoking the event, I was under the impression I could just invoke the event without a reference stupidly
You'd still need your listeners to reference the event invoker, but this pattern prevents you from needing them to reference each other. If there's only ever one source of the event, you can make it static, then the subscribers can get the reference to the event with ThatClass.OnUpdate += ... but events must be invoked on the class that defines them, so the event needs to be on the script that knows when it should activate
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Thanks for clearing this up it was my poor understanding of events I assumed that I could use them similarly to singletons but like you say its just to reference something happening without each script needing to know about eachother
https://hatebin.com/uvzsznbaqh why are the bullets going through the enemy?? The enemy should be taking damage
i have the bullets set a trigger and a box collider 2d on the enemy
If the bullets are triggers, they won't get the OnCollision message
OnCollision is between two non-trigger colliders
oh you are right
should i make 2 types of bullets one for enemies and one for player?
Why not use the OnTrigger method you already have for both enemy and player?
Just drop all the code in OnCollisionEnter into OnTriggerEnter (and modify it to use collider instead of collision)
it wont let me make another ontrigger
No.
Put it IN the SAME ontrigger
You don't need a second one
I don't know what to change
everything worls except for the red and black tetrominos and I don't know what I am supposed to do
Didn't you say your teacher was writing the code for you? Why not ask them to resolve it?
actually, I am not in school anymore since that was my last year and I was looking at tutorials to make that, I don't know what went wrong
Lookin to create a shotgun in my project but having some difficulty wrapping my head around raycasts. I currently have it setup to shoot in the direction Im looking but not sure how to randomize which direction the raycasts point in.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, shotgunRange))
{
Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}```
if you google "unity shotgun raycast" you'll get plenty of results with examples of how to randomize the direction of the rays within some parameters for the shotgun blast
My best suggestion is learn to debug your code and log the coordinates of your blocks, specifically this value right here:
Vector2 pos = FindObjectOfType<Game>().Round(mino.position);```
I did but most were already setup with their own weapons involving different systems they implemented
ex. most dont use ScreenPointToRay or have different raycast setups
Make sure these values match up correctly to what should be inside of the grid, because even though you're using row/columns, your game is still using approximation for the position, thus casting floats to ints (basically rounding your values down to the nearest integer)
raycasts have always been an issue for me 
well in that case if you don't want to use a different setup then you can keep your multiple rays in the same spot 🤷♂️
I just wanted to see if anyone had advice on how I could implement it with mine without having to redo the whole system I had setup, like wouldnt it just be possible to adjust the direction of the ray after its been created
the only thing you need to change is how you construct the ray
but if you refuse to even bother reading about how to do that, why should anyone put in the effort of explaining the exact same things you'll find in hundreds of google results?
thought Id just ask
u really should search up youtube there are literally tutorials for ur issue
boys,how i should change a text mesh with script? ``` private void Start()
{
healthText.text = "Health " + Health.ToString();
}
like that. but you probably want to do that when the Health variable changes rather than just in Start since Start only runs once in an object's lifetime
do you currently have a problem with what you have?
I did, and the only ones there were not the best tbh. One video was literally just uses multiple if statements and adjusts the values in set increments rather than it being random
another was 30 videos deep into a fps controller series
I don't know what I am supposed to change
Ill try and see what I can take from them
nono, it will also change constantly when there is some change ```public int Health = 100;
public GameObject player;
TextMesh texthealth;
public int getHurtWithCollideObject = 2;
private void start()
{
healthText.text = "Health " + Health.ToString();
}
private void OnCollisionEnter(collision collision)
{
if (collision.gameObject.CompareTag("Toilet") && collision.rigidbody.velocity.magnitude >= getHurtWithCollideObject)
{
takeDamage((int)collision.rigidbody.velocity.magnitude);
}
if (collision.gameObject.CompareTag("Toilet") && collision.rigidbody.velocity.magnitude >= getHurtWithCollideObject*2)
{
takeDamage((int)collision.rigidbody.velocity.magnitude/2);
}
if (collision.gameObject.CompareTag("Explosion"))
{
takeDamage((int)Health%50);
}
}
override takeDamage(int damage)
{
healthText.text = "Health " + (Health =- damage).ToString();
}
just use some Random.Range variables where u want it to be random
again, so what's the problem?
I wasnt sure if using multiple if statements for each pellet was good code practice like the video was showin 
let me guess, the issue is actually that you are getting a NullReferenceException because you never assign the variable anywhere?
first, make it work, then make it better/performant if you have issues . . .
nothing wrong with if statements but there is no need for one for raycasting shotgun except if(you hit) do that
the problem is that it does not show the health variable on the screen
yeah ❤️
do you have any errors?
nope,on the script no
You want to debug the Vector2 there, and you also probably want to some white space or filler text after the foreach
yeah so stop ignoring the errors in your console. make the variable either public or decorate it with the SerializeField attribute and then drag the relevant TextMesh object into the inspector
in the unity console?
?
yes
bruh, you should start with that. any error means smth wrong or bad happened. we can't do anything until all errors are fixed . . .
the error is: NullReferenceException: Object reference not set to an instance of an object PlayerHealth.Start () (at Assets/PlayerHealth.cs:14)
With your initial accurate and perfect shot, just apply an offset to each pellet's final destination. You could use random inside unit circle with some scalar and just add that offset to the target. The result would have raycasts shot towards those points rather than the center.
I do not understand what you mean
ok i will try
Research debug. You need to know that foundational concept
you're using a variable called healthText in your code but you have a field called texthealth. those are two different names . . .
The positional variable, throw that into your debug.log there :)
i don't see healthText created anywhere in your script. you should have errors in your IDE . . .
on the script the name is correct,maybe is the error of the message i sent 😅
how do you send code with incorrect text, that doesn't make sense? which is it? send the correct !code so we can see where the issue lies . . .
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I don't get where I'm supposed to put it
Where should I apply the Random.InsideUnitCircle offset to in the code?
like
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit + Random.InsideUnitCircle, shotgunRange))
{
Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}``` since its a vector3?
or someplace else?
Debug.Log can take values. Not just words you enter.
Try putting the VALUE in there
Just having "rotate" is useless
You'll have to think about it. You'd only want one raycast for the origin.
what am i supposed to write?
so im back, still struggling with getting this vector 🥲
Mao mentioned positional value... so what do you have there that has to do with positions?
I still don't get it what I am supposed to do
What value is a position. In your code?
Right here
#💻┃code-beginner message
Honestly, I didn't see the beginning, I don't even know what you want to fix. Mao said log position, and you literally have a variable right there
I. still. don't. know. what. I. Am. supposed. to. do
How can you not? I don't understand. No offense, but wtf lol
here
The idea is your check position is not returning false despite your blocks going out of bounds, so first let's see what those values are
Put... the position... value... in the debug.
How could you possibly not understand that?
what values?
Are you trying to log the words "position value"?
I do not know what I am supposed to write
What do you want to log the value of
I don't know why the red and black tetromino are the only ones that are like that
Where did you read up on this tutorial btw just curious
I wouldn't suggest doing tetris games by aproximation in the future. You can easily just do a 2D array and check via index.
As I said before, read about debug.log
You have a profound misunderstanding about how they work. You can do this
int value = 3;
Debug.Log(value); // this will show a 3
So put the VALUE in there
thanks for the tip on Random.InsideUnitCircle
Evantually figured it out by doing this
{
Vector3 direction;
Vector2 randomSpread = Random.insideUnitCircle * spread;
direction.x = randomSpread.x;
direction.y = randomSpread.y;
direction.z = 0;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition + direction );
RaycastHit hit;
if (Physics.Raycast(ray, out hit , shotgunRange))
{
Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}```
just so you know, if you ever plan to visualize these rays, they don't start at the same place. the directions are also all just straight so you may even notice some issues with them potentially hitting things they wouldn't otherwise hit if you just randomized their direction a bit
ok again, I have a problem and it is due to the speed detection of an object when it collides with another, in my case if my toilet object collides strongly with the floor, or another prop or is shot, it will explode, but my problem The thing is that if I drop it at 200 meters for example and it crashes into the ground or something else, nothing will happen because it seems that the speed value is very small and to explode against an object it must have a certain speed, which is a public variable ( for example 7 speed and I am using rigidbody.velocity.magnitude)
holy hell mate, did you take that printing the integer 3 as what you literally need to do instead of just an example of how you can print relevant information to the console?
why is the enemy heath bar not decreasing when the enemy is losing health? https://hatebin.com/ojqpdaalzg
XD
will look into that, thx
Okay, so, you should probably stop waiting for someone to write the code for you and instead read the words people are saying and put a bit of critical thinking into it
?
No one is going to write the code for you
any errors in the console?
I only did what I saw
nope
is it printing the correct fill amount or is it printing 1?
its not printing it
if it isn't printing then that code is not running
show the script
(they did)
mmm
I still don't know what I'm doing wrong
either something else is changing it, or you are operating on a different image component than you think you are
log the fillAmount before you change it as well
What is the value you want to log
Yall how to make the player not affected with gravity while dashing ,so it dashes on a staight line
what value?
set its gravity scale to 0 for the duration of your dash
i did but still didnt work
probably also reset its Y velocity to 0 immediately before the add force as well
Also ur the guy that teached me Github lol ,thank u
what. value.? I don't get it
i also have this in my update methode
What is the thing you're trying to print
My code wasn't for you to copy..... it was an example.
I just don't get they are the only tetrominos that just goes right into the wall after rotating near it
WHY WOULDNT IT WORK 😭
have you bothered logging the position being checked in your CheckIsValidPosition method?
Set the Y Velocity to 0 before setting the gravity scale to 0
just to be clear, do you want it to move only horizontally when it dashes?
rb.velocity = new Vector2(rb.velocity.x , 0f);
?
exactly
like this?
christ, mate
:)
Do you want to print the word CheckIsInsideGrid?
u mean this? rb.velocity = new Vector2(rb.velocity.x , 0f);
?
Is that what you're trying to do
you could even just set the entire velocity to 0 if you don't want the horizontal movement to affect the dash distance too
Tell me, what do you think Debug.Log does
Ayy that works , btw i also want the dash to happen in a short time ,like 0.1 sec or so
I don't know what I am supposed to write, the tetromino red and black tetrominos are not supposed to go into the wall when rotate like the other tetrominos does
You want to know their positional values to fix the issue
And you've been told to use Debug Log to view the value of the variable that might be causing the issue
And it's been almost an hour and you haven't logged it
first we need to log those values and print them to the console
that's what your dashingTime variable is for. you can reset velocity back to 0 again when the dash completes to ensure that the force is no longer affecting the rb
I still don't know what I am supposed to write there,
Log
The
Position
how do I Log the position?
inb4 "Debug.Log("the value");"
Seriously, debug log should literally have been the first line of code you ever wrote
This should not be hard
this should have been squared away before you did anything else
Neat, is that some unity AI
nah, it's vertx's site
No that's all written by Vertx
ah, I see
who got tired of answering the same questions so much he bought a domain and made a site
Called it
I don't know what I am doing right now
yes that is clear
We can tell
you should go do some basics of c# first
debugging shouldnt be the hard part of this
How did you get so far without ever debug logging a value
Again, this should have been the first line of code you ever wrote. Every tutorial that explains unity will start with a debug log
If you didn't, you skipped an important starting step
I am not good with complex writing
This isn't complex writing
it's putting a variable in a log
Examples are shown in #💻┃code-beginner message
I know that but I still don't know what I'm doing with it
you've already been told you need to log the position(s) you are checking
You'd want to log the position and see what's not behaving as expected.
what position?
do you just not know what your CheckIsValidPosition method does?
I'm assuming pos
The position you're checking if is valid or not
Find out what position is not doing what you expect it to do
the rotating one, yes
So log the position so you can see what the last value of it was when it does something you don't expect
I don't know how I can log the position
you put the position
in the log
as the parameter
the image is the fill icon because i have it set in the prefab place.
I don't know what I' doing
do you know how to call a function
and pass in a variable
if not then you should not be doing any of this
you need to learn the basic syntax of C# first
Then make a game
I do not collect
At this point, we cannot help you. You fundamentally do not understand enough C# to even get an answer at all. Even if we could get the logs to find the information enough to find out what the problem is, you would not be able to understand any solutions we give. We cannot go further until you learn how to at least communicate about code
... I'm going to cut my wrists
suicide is not a joke. seek help
Go through the intro to C# tutorial I linked, and go over the documentation you've been linked for how Debug Log works
all I did was look at tutorials and did what they said and I don't get why this is happening with jsut the black and red tretromino
We are fundamentally unable to communicate any solutions to you until you at least know what code terms mean
I know the documentation but I still don't know what I'm going to write
Tell me, how do you call a function in C# with a parameter
use chatgpt
If I have a planet with slots and slots have resources you can mine + you can build buildings, some of them mine resources others craft stuff from inventory im just going at it but sphagetti is forming lol how would topology or how u call it look like, what is a slot what is a building how it all ties together
They can't even understand a human explanation, a spambot will not help
I won't restart everything to the start
bro why u even arguing
you dont need to restart just put your code in chatgpt and ask it what is wrong
it will tell you the problems and how to fix it
bro u gotta give perfect prompt for it to do that and at that point its programming again lmfao
you do not need to restart, what you do need to do is go through your code line by line and understand what it is doing
worst advice ever
how?
because then you do not learn
chatgpt is** a mixed bag. Even if you are trying to learn from it, you still need to distinguish from that it* may be wrong about
I don't know why it's doing that, everything in tetris works perfectly fine with all the tetrominos when I go next to walls and rotate and I do not go in the walls, but the red and black tetrominos does, I Just odn't know why just these 2
I've had some success learning some graphic apis earlier this month with it. It's pretty good when your questions are usually in the documentation as it does seem to be trained on it.
The rotating piece likely goes against the wall and when flipping again something magical happens. This something needs to be debugged.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
well to start with, you are thinking in colours not shapes, look at the shape of those pieces and think what happens when you rotate them
I still do not know what shape red and black are
they are S ans Z Tetrominos
they are S and Z Tetrominos
Ok, so where is their pivot point, how do they rotate?
ahhhh geez i dont know ive been making game for far too long already and i dont knwo what to do anymore... i already had it finshed, compressed the whole game folder to upload it to itch.io but then i noticed it occupies too much memory (around 1.50 GB) and i realised i absolutely forgot about optimizing it. then i started deleting some assets to optimize the game and i fully destroyed it. the biggest problem i have now is that when the player and the obstacle collide, the obstacle doesnt destroy and the game does not restart itself. it says i should use DestroyImmediate() method instead of Destroy(), but when I use it DestroyImmediate(), the console complains that "destroying components is not permited"
obstacle's script: https://gdl.space/bajewepuci.cs
and player's script: https://gdl.space/efoyanopit.cs
I don't know where I can see their pivot point
so how can you rotate them if you do not know that?
When it says that, it most likely means you're trying to destroy a prefab instead of an instance of it in your scene. Unity prevents that so you do not lose your asset in your project files
it's been a year since I last worked on it, I don't rememebr much
@hushed hinge It strikes me you have done an awful lot of copy paste and almost nothing in understanding what you are doing
I was only looking at tutorials
man, dont be a child, I work on programs I wrote 45 years ago without any problems whatsoever
DestroyImmediate() is usually used for editor scripts. You should be destroying stuff during the runtime, not in the editor.
Line 25 of ExplodedObstacle is probably the culprit, you do not use the result of Instantiate one line above it
Actually, it's line 27, you're calling this on the prefab
You are supposed to learn from tutorials, not just copy them
yeah i have two prefabs of the obstacle, one in whole and one is made out of smaller pieces cause i wanted it to explode and scatter around when they collide, but it did not work work and it still doesnt work...
Again it is because you are not using the return value of Instantiate on line 24
i guesss i can just give up on the scaterring around part
Compare with how you're doing it on line 36
If you're going to follow tutorials, follow along and type as they do. Don't just pull their code from their repository. If you don't understand it after all that, do it again or ask questions here about specifics.
should i write it like
GameObject scatteredObstacle = Instantiate(explodedObstacle, transform.position, Quaternion.identity);
Destroy(originalObstacle);
?
ahhh wait how do you properly format it?
And then use scatteredObstacle yes, on line 27
remind me of how to format code blocks please ^^'
```cs
// Code
```
aaahhhh without the space
it rotates from there
thanks, im usually stupid ^^'
I asked in chatgbt and added more details to my saying for it to understand what is wrong with my script
so your pivot point is in the wrong place to start with
Pivot looks good to me for the SRS version (used by most games), but there's a lot of them
Most of them use a 3x3 grid for rotations, except for the straight bar
No, pivot should be between the blocks, not in the center of one of them
Nope, if you do that, on half the rotations your tetrominoes will be misaligned on the grid
I think Tetris has them on individual blocks
in a 3x2 pivot is at 1.5, 1
The link I posted has images showing the pivots
struggling to GetAxisRaw
https://hatebin.com/vssatqdkqe how can i make it so that when space is pressed one time the text is skipped to the end of the sentence, and when clicked 2 times it is moved on to the next sentence
aaahhhhh why do i have to be so duuuuuuummbbbbbb
it still tells me that it wants me to destroyimmediate
that means you're trying to destroy a prefab instead of the spawned instance
here's the new script: https://gdl.space/eyirakegaw.cs
Make sure you're calling GetComponents* on the instance, not the prefab
Yup called it
Line 29
i dont know what and how and where to do this part
It's not relevant anymore because you're doing it now
The issue is that you're not using scaterredObstacle on line 29
????
anyone able to help with this?
wait should i use scateredObstacle instead of rbs?
GetAxisRaw is a method on the Input class
but it doesnt work for me?
have you even tried it?
also vector3 doesn't have .position
its already a pos
oh no wait instead of explodedObstacle, huh?
scatteredObstacle.GetComponentsInChildren<Rigidbody>();...
yeah omg im so stupid
When did you use it
InputEvent is not Input, check again
but then i dont have to change anything on this line, right?
rb.AddExplosionForce(Random.Range(minForce, maxForce), explodedObstacle.transform.position, explosionRadius);
(line 32)
meaning when i type the getaxisraw
i want to destroy the originalObstacle when the player collides with it and i have it on line 36, but im not sure whether it'll work this way?
Have you actually tried using it? Show the error you get when you do
Isn't this script attached to the obstacle you want to destroy? In that case that would be a simple Destroy(gameObject) to destroy the object this script is on
Also not sure why you're instantiating a new exploded obstacle on line 39 just to play some particles, you can do this on the one you instantiated on line 25
aaahhhhhh i wanna cryyyyyyy
yeah i just figured xd
its just that i already got too much help from too many people on this game and so the game got really confusing
i had it all complete but i did not optimize it, and when i started deleting the assets i thought i didnt need anymore i basically deleted half of the game
also yes, it is attached to the obstacle i want to destroy, i.e. originalObstacle
ie. gameObject
You do not need originalObstacle because it would be like referencing yourself, it's unnecessary
You didn't drag-drop the object itself in the script's Inspector did you?
Hello guys, is this expected behavior for child prefab objects? I am trying to override the color but it keeps reverting back when I want to apply it
Does this script have a custom inspector?
Yup, I just realized that I have some stuff in OnValidate that are resetting the values back
I was freaking out for a while
i think the build doesnt include anything it doesnt need, i could be wrong though
Does anybody know how I can make it so that a Parent object always visually appears over its children?
I have a Prefab which contains a TextMeshProGUI as the main object/prefab source, and an image child I want to appear BENEATH the text. I could fix it so that the main object is the image, with the text as the child, but I just want to know if what I asked is possible, as it will make it much easier for me instead of having to re-write tons of different scripts.
You can try canvas grouping
such that you create an additional canvas and then order them with that. Otherwise you can try swapping the hierarchy around at times but that's dependent on your use case.
"and an image child I want to appear BENEATH the text."
You can just add the text as a child to the image component
Yeah, I'll probably just do that. I just wanted to see if another method was better before I went ahead and re-created the Prefab and fix the scripts. All good though!
My reading comprehension is bad, but the grouping idea does work for some situations, though reading it again, yeah just child the text ;)
what's the smartest way to map all 20 faces of an icosahedron to values? 
I have a low poly mesh of the 20 triangle faces, but I'd like to return dice roll results from that
My naieve guess is that I could somehow convert vector3 euler angles to dice results? But I have no idea what vector values every face would be, seems error prone on my part trying to divine that info
that also might not work either because if the mesh isnt sitting perfectly flat, the euler will be some other value 
Smartest way would be pure math.
Friendly way would be empty objects placed in the center of each face rotated outwards with a simple component to give it a value property.
Either way, when the dice stops, you find the face whose dot value with world up is closest to 1 to get the most up facing value.
oh I see what you mean, game objects on each surface, that is very friendly but less cool than doing it with math
But I suck at math 
I'll try game objects for now but I feel like thats going to mess up the results because I won't be able to perfectly position each object's vector3 position dead center of the face
You don't need to always go the smartest route, the alternative is fine.
You don't actually need to position them perfectly, it's their rotation that matters. I only said put it on the face for visual ease.
ayo new unexplainable issue just dropped how this could possibly keep printing that log if panel is already activated I use same thing in statement and activation so its same game object https://hatebin.com/jzdzhodumt
I already fixed it by referecing gameobject directly without getting it from animator but what the hell
Having an issue with debugging, couldnt find any resource online with this issue, but Im trying to do Debug.DrawRay, but the rays only appear onscreen for a quick second before disappearing
not sure if its because I have debug.drawray in update() or something else but I dont know why they quickly appear and then vanish
{
Vector3 direction;
Vector2 randomSpread = Random.insideUnitCircle * spread;
direction.x = randomSpread.x;
direction.y = randomSpread.y;
direction.z = 0;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition + direction );
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 100, Color.green);
if (Physics.Raycast(ray, out hit , shotgunRange))
{
Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}```
use overload where u can set its duration
That's how they work. If you want them to draw for longer use the duration parameter or call draw repeatedly
gotcha, sorry haven't used drawray in ages so I wasnt sure if thats what it was supposed to do
I’m having trouble making my camera follow my character like have the camera alwsys behind my player even when I rotate but what I have now is it kinda rotated at a different speed than my player so it starts off behind my player then can end up infront of my player or to the side of it can anyone help me
I recommend using Cinemachine instead of custom coding a camera script
you can get the behavior you want in a few clicks instead of bashing your head against code
is there any way to fire a ray or something similar, and then get the direction of its bounce? im trying to create a realistic mirror.
sure, a raycast combined with https://docs.unity3d.com/ScriptReference/Vector3.Reflect.html
thanks! this is exactly what i was looking for.
public Transform mirrorcam;
RaycastHit bounce;
Vector3 bounced;
public LayerMask mask;
void Update()
{
Physics.Raycast(playercam.transform.position, mirrorcam.transform.position - playercam.transform.position, out bounce, Mathf.Infinity, mask);
bounced = Vector3.Reflect((mirrorcam.transform.position - playercam.transform.position), bounce.normal);
mirrorcam.transform.rotation = Quaternion.Euler(bounced);
}
this is the code i wrote, im trying to reflect the way that light reflects off of real mirrors, but it isnt working. it wiggles on all axis, but very subtly. are there any obvious problems in my code?
can u show the class initialization as well?
sure. here.
using UnityEngine;
public class MirrorEffect : MonoBehaviour
{
public Transform playercam;
public Transform mirrorcam;
RaycastHit bounce;
Vector3 bounced;
public LayerMask mask;
void Update()
{
Physics.Raycast(playercam.transform.position, mirrorcam.transform.position - playercam.transform.position, out bounce, Mathf.Infinity, mask);
bounced = Vector3.Reflect((mirrorcam.transform.position - playercam.transform.position), bounce.normal);
mirrorcam.transform.rotation = Quaternion.Euler(bounced);
}
}
after much data entry and determinine of values, got it werking 👍 Thanks for the help
Awesome, nice work 🎉
You're treating a direction vector as if it were a set of euler angles
which is ????
Quaternion.Euler(bounced); makes no sense
maybe you wanted Quaternion.LookRotation(bounced);?
ah yes, thank you!
it works great now but is there a way i can make it only rotate on the y axis?
zero out the y component of all the vectors you're dealing with
zero out?
with Unity's Script Execution Order, does that play nice with Inheritance or do I have to specify everything
ie. if i have UIManager before Inventory, Will everything that inherits from Inventory go after UIManager?
Unclear. Try it and let us know
Hey, if this code is being executed in the update, does it mean that rays will be generated continuously every time the E is pressed without deleting anyone? Is there a way to avoid it so that there is no lag? ``` void Update()
{
if (Input.GetKey(KeyCode.E))
{
objectAnimator = gameObject.GetComponent<Animator>();
ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit, interactDistance) && hit.collider.gameObject == gameObject)
{
InteractWithObject(gameObject);
}
}
}```
Why is my sprite so offset from the origin? It's the only object in the prefab (there's no parent or children here) and yet it's really offset from where the actual object "is" for some reason
it means I have to offset the circle collider 2d to get it to match up
wdym by "without deleting anyone"?
some ray
welp,first of all is that true that i say?
I have no idea what you are saying
the code will run every frame since it's in Update
beyond that I don't follow what you're saying
if (Physics.Raycast(ray, out hit, interactDistance) && hit.collider.gameObject == gameObject)
is this code you're trying to put on interactable objects?
So a ray will be generated every time I press E and they will accumulate? since the code is in the update
wdym by "accumulate"?
Rays are temporary
rays are not persistent objects that live in the world
because none of them are erased
a raycast is just an instantaneous computation that happens
ahhhhhhh
there is nothing created that needs to be erased
thanks so so so muchhhh 😘
that being said this is very inefficient if this is a script you have on many objects in the scene
oh, I think I found my answer - this particular sprite is from an animation and I think the animation has it displaced?
you'd be much better off just having a single Interactor script on the camera that does a single raycast each frame. Rather than doing one raycast per interactable object.
do you know how to do that?
I just explained how to do it basically
you just do one raycast per frame. Call an Interact() function on whatever object you hit with that one raycast
oka
You also don't want to call getcomponent there. You are using gameObject which is the gameObject that script is attached to, so just do it ONE time in awake or start
I know you are rewriting this, but the point still stands
So OnCollisionStay won't work with a ray?
wdym work with a ray ?
A raycast doesn't produce or possess a collider, so no it wouldn't cause any OnCollisionX nor OnTriggerX messages to be sent
I thought a ray would create a Collision or Trigger event on what it hit.
A ray detects colliders
yep, and in detecting them, I thought it could also activate them. I was wrong.
right, thats something you code through the collider component when is found with araycasthit
A ray is just an imaginary math concept. It means a point and a direction
Rays don't "do" anything
A "Raycast" is a math operation in which you find the intersection of a ray and any colliders in the scene
but it can "hit" something... it was just a misunderstanding
casting is the physics part ye?
it did to me a minute ago.
so does a raycast hit create a collision or trigger event on the object it hit?
No
ok.
say I have a player and I want there to be an evil cloud that when the player enters the cloud, I want something to happen. should I put the collision script on the cloud or the player? and should I mark the cloud as a trigger or not? right now I have the script on the cloud and if it's a trigger the player walks through it without the special stuff happening (no collision reported) but if it's set as not a trigger, when the colliders touch the thing happens, but the player can't walk through
trigger would be better no?
Sounds like you want a trigger collider and for the logic to be on the cloud script
when I do that then collision doesn't report
"no collision reported" means you're likely just doing it wrong
Show what you tried
it's a very simple script...
void OnCollisionEnter2D(Collision2D other)
{
print("player entered!");
}
OnTriggerEnter for triggers
OHHH
Look up examples
thank you!
Hi, is there a way to be able to make it so i can write the bool parameter of an animation in the inspector? I commented what I'm after. Hope it makes sense
like a string?
make a public bool, no?
You want to assign the bool parameter, like the parameter name or just the value?
Just make a public bool field, no?
Or I guess a string if you meant the parameter name and not the value
Use a string to access the name for StringToHash to get its anim id or just use a bool variable to assign its value. Not really sure which one you want . . .
What I want was the access the name. I'm aware about the public bool. So StringtoHash is the way to go?
StringToHash is more efficient for the animator to lookup that parameter
Thank you. I'll look that up
To start with you can just use a string
Thank you. 🙂
I want to remove a game object from the scene when the player collides with it. Can I delete items from the scene with a certain tag from within my playercontroller script?
I already set it to change the animation on the player after they collide with the tag, was just wondering if I could also destroy the item with that tag from the scene, since it is a unique pickup. not like coins or whatever
or any better way to go about removing it from the scene. doesn't have to be destroyed.
But, I don't want the player to be able to see or collide with it anymore
If you want to destroy the object when the player collides with it, why do you need to delete an item with a specific tag? Just destroy the object on collision
How would I go about that. The item in the scene doesn't have a script attached to it.
but has a tag?
I was just using the item to change animation state of the player
How are you identifying when the player hits it
private void OnTriggerEnter2D(Collider2D football)
{
thisAnim.SetBool("hasBall",true);
}
if(football.CompareTag("YourTag"))
So, that's going to fire whenever this object collides with literally any trigger
that code is within the playercontroller script. So whenever a player touches the ball they get their animation set to that and hasBall is true
Whenever the player touches the ball any trigger they get their animation set to that
So it shouldn't fire unless a player touches it right? Or am I missing something
It will fire when the player touches any trigger. Is that what you want
I thought since I set the tag to football it was only checking for that
thats not a tag
You aren't checking a tag anywhere
Collider2D football) << I thought this is where the tag went
but.. that doesn't make sense. Navarone what you said about the compare tag is right
sorry for the dumb question.
That's the name for the variable
the parameter name is just for you
It could literally be anything and the code would be identical
It could be Collider2D TheChungasAmongus and the code would be unchanged
haha So I could refernce TheChungasAmongus within the code then. I see the use of that now
Yes, it's just the identifier by which you reference "The collider this object hits" in that function
Thanks for the link navarone. Sorry I need to brush up badly. Lots of stuff I don't remember.
So I can just use the if tag compare within my method
yeah
I made a public gameobject football
So I could assign the football in it so I can destroy it from within the playercontroller.
Is there a better way to go about that. I am thinking that when the ball is fumbled or thrown.. the public gameobject football won't be set because I had to manually drag it in.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
private void OnTriggerEnter2D(Collider2D hasFootball)
{
if (hasFootball.CompareTag("Football"))
{
Destroy(football);
thisAnim.SetBool("hasBall", true);
}
}
you should name things a little bit mor clear, hasFootballis just a collider2D should just be collider
true, that sounds like a bool variable . . .
Yeah I just changed that
should just be Destroy(collider.gameObject);
iirc colliders like transform, always have access the object their on
So I am thinking I should probably not destroy the football. when collided with
any component pretty much if its on a gameobject lol
if you want a specific one you don't need the field in the inspector, the reference
you're doing stuff to it, after tag checks out
Collider2D is the thing you collided with
So after they collide with the football the animation changes to look like its carrying the ball. If I do destroy the ball from the scene.. is it possible to place an object back into the scene if it isn't in the heirarchy?
if that even makes sense..
yeah thats pretty much instantiation
easier to just deactivate the object if you plan on spawning the same thing
Yeah I do just plan on only having the one football.
That can be fumbled handed off and passed
yeah you can reset positions and move it around even if its deactivated
as long as you have the transform referenced
the game object isn't actually attached to the player, I use the animation to show it is being held
So should I put a script on the football to follow the player, while it is deactivated?
no deactivated objects dont run script afaik
just set its position when you need it, or parent it
parenting essentially follows it without needing a script
There are going to be a bunch of players. I'm gonna have to look into making the football become a child of whichever player has it
Or I could add in the player script, when they pass the ball. reactivate the football, and then give it the players current transform?
you could also just have a main script that keeps the ball following whoever has control of it
football.transform.parent = transform;
something along those lines..
I like the gamecontroller script idea
could even be BallController
for keeping score.. stats.. time.. ball possession
ideally you want a a script to only deal with one thing
Do you find it better to keep all of that stuff in one script
or is it cleaner
ahh alright, that's what I was wondering
Im trying to toggle a UI visibility using code and and an if statement to show a you died screen if health reaches 0, but I cannot for the life of me figure out what to put in the if statement to toggle the UI on??? please help
What is your PFP of navarone. It looks bad ass btw lol
You should start by configuring !vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
It should not say Miscellaneous Files in the top left
^ It really helps out a lot
generated thru ai
how do I do that?...
Those links provided above
follow those, and you will be in a happy world of coding.
Thank you for the guidance by the way, I really appreciate it. You all are awesome on here.
You're welcome!
& yes its a good learning community
So with that main script that makes the ball follow the player. If football is deactivated. It would still be able to follow the player, since the code making the football gameobject move is on another FootballController gameobject
as long as the object is referenced yes you can move it while disabled
I configured VS, any help for the code?
I assume its pretty simple I just dont know what im doing
show us its configured @tropic crown
ty
so what do you want to toggle exactly?
I have a UI of a black screen and a child text that says you died*
you have that gameobject / blackscreen referenced yet?
I assume you died is on the gameobject you want to toggle ?
yeah
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.CompareTag("Football"))
{
thisAnim.SetBool("hasBall", true);
football.SetActive = (false);
}
}
won't let me do that within a method group
Hey guys, does anyone know what I did wrong? Lets say I have a GameObject that has a script connected to it that is using OnDrag, OnBeginDrag and OnEndDrag.
This is the script (Test Script)
https://paste.ofcode.org/cUMhXZXezDUVHJzdPbLGzw
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class TestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag");
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
}
}
Now on the GameObject, I added an Event Trigger in which I added the Begin Drag, Drag, and End Drag and I conncted the same GameObject with the script to it.
But for some reason when I looked up the function, the options for OnBeginDrag, OnDrag, and OnEndDrag weren't there.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
SetActive is suppose to be a method, no?
CS1656 Cannot assign to 'SetActive' because it is a 'method group
also don't crosspost :p
Right... so... Are you assigning false, or calling with argument of "false"
it's a method not an assignment
methodsHaveParenthesis(somethingHereSometimes)
The problem here is that you have a equal sign there. I am unsure if this was intentional, or by accident.
I was just trying to disable the game object and i saw that SetActive was the way to go about that
I was trying to do it within my if statement
it is but its a method
methods don't use =
when in doubt always look at the !api
💻 Learn in detail about the scripting API that Unity provides https://docs.unity3d.com/ScriptReference/
i get you both now.. just so used to always using = when writing true or false
= is for assignment
right and the setactive method im using is false
not only for bools
Try Pomodoro timing. Helps destress your brain for long stressful work environment.
I'm surprised that your IDE doesn't tell you that you have a problem here.. Would recommend reading the pinned #854851968446365696 post @valid finch
is it a good idea to use scriptable objects for switching scenes? I want my player to keep his position as where he enter when he gets back to previous scene and also keep the data like the inventory and when the player picks up an item from previous scene and switch to another scene then get back, the item shouldn't be there
You could just make the player [DontDestroyOnLoad]?
Or have the player save information before loading a new scene, and then instantiate the player after scene loaded.
Never heard of that, I just googled that. Sound like a good way to work
Scriptable Object should be used as a template instead of items.
it's wild but SetActive is an internal C++ thing lol
I assume is just doing some extra magic but in a nutshell the method passes the bool
I should program in c more often..
Kind of like the Update() is internal
yea Update is calling the C++ side
Isn't it backward? Update is called from the c++ side...?
unity's c# is just an API essentially to the c++ engine
Any good google search ideas to find a list of internal built in methods within C#
apparenetly every Update is calling the C++ side, so even empty Updates can indeed call the backend
Like a list of things like Update() Start() FixedUpdate()
are there more I am missing
I'm confused. Update is invoked from C++, and any API you interface with Unity is directly calling interops to C++...
Awake(), LateUpdate(), OnDrawGizmos(), OnGUI(), OnTriggerXXX, OnCollisionXXX, yes there's a lot more.
Something like this might help you https://docs.unity3d.com/Manual/ExecutionOrder.html
Very awesome link
thanks
not sure how it all works behind the scenes tbh I just remember reading this so I avoid keeping Update anywhere and try to limit its use
sauce : https://resources.unity.com/games/unity-e-book-optimize-your-mobile-game-performance
Gonna get back to work. Just a random question, out of curiosity is it possible to change executionOrder. I don't need to do that, just like to learn some new stuff
And like to know limitations
Yes! - See this https://docs.unity3d.com/Manual/class-MonoManager.html
Update is called from C++ land. The first time a mono type is initialized, it uses reflection to gather all the "magic" functions like Update, FixedUpdate, OnEnable, etc, grabs their pointers, and sends them off to a buffer in the internal code. Which then calls the function via that pointer.
As per the actual Unity execution order - no. You cannot change Unity's event flow.
SendMessage() is expensive. That's sort of what unity uses to send signal to events such as Update() and FixedUpdate().
Thank you, You earned that brain in your name 🙂
Ahh I see, that makes sense
kinda wild how empty Update/Events can still allocate resources
Oh do I have a resource for you https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html :)
https://medium.com/@thebeardphantom/unity-2018-and-playerloop-5c46a12a677 good read on changing the order
This seems excessive... To go as far as to change the game engine's loop order...
afaik if you start depend on changing scripts order, something in the whole system is flawed somewhere
If it's flawed, it wasn't considered initially.
I've used it in a few projects where I just needed a renderer and my own execution loop
It's quite nice
Speaking of dangerous code, I'm dealing with JNI and unity's interops.
I probably wouldn't reorder it but injecting stuff is very normal 😄
@queen adder #archived-unitytips is not for questions, provide your !code properly with context
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.CompareTag("Football"))
{
thisAnim.SetBool("hasBall", true);
football.SetActive (false);
}
}
------------------------------FootballController Code Below
void Update()
{
football.transform.position = following.transform.position * Time.deltaTime;
}
The ball gets disabled upon triggering, but the hasBall animation isn't activating.. is it happening too fast or something?
Cuz It is definitely immediately moving to the player's location
check the Animator at runtime to see if all the transitions are working
also whatsu up with that Time.deltaTIme on the follow code lo
bad habit
nothing is showing up even though I'm getting the default running animation. although it should be the hasBall animations
The running animations are working as they should
but not transitioning anymore. They used to transition when I had the ball not following the player
make sure you selected the instance running animator not the one in project window
also show transition for hasBall
It's working now
The animator isn't showing realtime inputs while in gameview though
That time.delta time was messing it up or something..
Just curious why the animator isn't showing live blend tree changes while playing
It's not a giant deal right now. Was just wondering why it isn't showing. Gonna call it a night shortly.
it does if you select the correct object that is playing that animator
its a bit tricky
usually is..
when I started and wondered why none my transitions were working :p
I wish I could move my blend tree around like I can with the base layer
thats just nitpicky stuff. it really doesn't matter
Goodnight, thanks again
A people know how i can make a local game ? Like i use 1 controller for control my char and the other people use a other controller
Look into the new input system.
Ok i gonna look that ty
How to avoid such code duplication in classes? They have a difference of a couple of fields.....
Inheritance
I use interfaces, due to the fact that multiple inheritance is prohibited 😦
I mean
Definitely ought to couple the shared members into a single base class if they do the same thing.
Or, if inheritance is really not what you want to do
Then you could create a class / struct inheriting from nothing, containing all the shared members
and have it as a field
Correct, not everything needs to inherit MB
A class would inherit item and interface the iweapon.
I didn't understand(. please rephrase
interfaces cannot inherit from classes
but what should I do if the code in Item is the most repeatable
c# not allow multiple inheritance
so you should first define a base class inherits from SO then your custom class inherits from this class
or use composition instead
C# allows you to inherit from multiple interfaces, but from only one class. Try to change Item from abstract class to an interface.
Hello everyone !
I need some help simulating/triggering a mouse click in the interface of my game.
In my game, the player can use either keybaord+mouse or a controller to play. I and them to be able to use the controller in the menu of the game.
Since the interface of the menu is not a usual grid with horizontal/vertical movement between things, it's not great to simple show the focused button, and I have chosen to have the controller move the mouse in the menu, even though I know it's not a great UX.
I have already written some code that let me move the mouse with the joystick of the controller (without preventing mouse movement at the same time), but I can not figure out how to make it click the mouse.
Here is my current code :
https://hastebin.com/share/ogutupacaj.java
This code is called in the Update function of my menu.
Can you guys help me ?
is it possible to inherit an interface from an abstract class?
An interface can't inherit from anything
the first screenshot is the code that gpt wrote... I was deceived(((
Don't use GPT...
Unless you already know how to code, and know how to differentiate working and non-working stuff, it's a very bad tool to code
SO Item
SO Weapon : Item
SO Range : Weapon
SO Melee : Weapon
...``````cs
SO ItemsInGame
Item[] items;```
anyone have experience with the UnityGoogleDrive plugin? not sure what this means
nvm, turns out I wasn't handling the url correctly

problem solved, now I have a byte[] of a .obj / .fbx file. how do I turn it into a unity object?
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class CharacterControllerFrom0 : MonoBehaviour
{
CharacterController _characterController;
[SerializeField] private float _moveSpeed = 2f;
[SerializeField] private float _jumpStrength = 2f;
[SerializeField] private float _gravity = -9.81f;
private Vector3 _velocity;
// Start is called before the first frame update
void Start()
{
_characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
MoveForward();
ApplyGravity();
}
private void MoveForward()
{
_characterController.Move(transform.forward * Time.deltaTime * _moveSpeed);
}
private void Jump()
{
if( Input.GetKeyDown(KeyCode.Space))
{
}
}
private void ApplyGravity()
{
_velocity.y += _gravity * Time.deltaTime;
}
}
Hey all. I'm using character controller component and this is my code. I'm trying to apply gravity but cannot seem to get it work.
you need to actually use that _velocity variable somewhere
Apply gravity before moving
Also with CC you'll want to multiply gravity by delta time twice
Example from the docs https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
Thanks.
"A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details."
uh.... how tf did I manage to create a memory leak in C#
have you been using any native collections in your own code (such as with the jobs system)? if not, then it's likely just an editor error and you can restart the editor if it bothers you
IEnumerators belong there, dont they?
no
in that case I dont think I have
i'm not talking about the System.Collections namespace. i'm referring to unmanaged data structures that unity provides in its code base
like NativeArray and NativeList
I dont think Im using any of that considering I dont even know what they are
well then if the error bothers you just restart the editor
and again, if you are not using any native collections in your code you can safely ignore it as it is likely just an editor error
Im just gonna pretend its not there until it breaks something
something doesnt feel right tho... Im getting really low fps
use the profiler if you have performance concerns
Hello everyone , i cant seem to get Cursor.Setcursor to work / Appear in my project
Is there any packets or something that i need to have before it works?
Did you do this
Are you referring to this one? https://docs.unity3d.com/ScriptReference/Cursor.SetCursor.html
Yeah im using that as a reference
Texture seems to work on everything else , just that the Cursor.Setcursor doesnt exist
you've probably made your own Cursor class or a variable called Cursor
Checked that , nothing called cursor
You have using UnityEngine, right?
hi im trying to make a gameobject active when pressing the Z key while the player is colliding with an npc.
the player does stop when the player's and npc's collider hits, but nothing shows up on console logs when they do, so pressing Z does nothing
https://gdl.space/ibelesanaw.cs
share the full script
Does your IDE detect other unity classes (is it configured)?
I found the problem
UIElements has a Cursor function
Ill just have to make a new script for the cursor specificly for this one.
Thanks for the help 🙂
just use the fully qualified name UnityEngine.Cursor or a using alias
Are they in trigger mode?
That.... i didnt think of that xD
Thanks alot. That helped
neither of them are
OnTriggerEnter2D implies you're doing a trigger event rather than a collision event. Also 2d.
Then use the non trigger variant
OnCollisionEnter2D
With parameter type Collision2d
hmm after changing it to
{
Debug.Log("player colliding with npc");
}```
it still isnt working
how do you make the camera consistent with different monitors?
care to be more specific about what exactly you are referring to?
When running my code as a program it makes everything really small when in the unity editor it's the right size
are you referring to your UI objects being the wrong size/location?
Gimme a sec I'll get a screenshot
The red box is what it looks like on the unity editor
so yes, your UI. see the documentation pinned in #📲┃ui-ux to learn how to anchor and scale your UI objects
swag ok
I want the Agent to start jumping from the beginning after a fall, but it seems that it won't recalculate the path unless I execute Agent.CompleteOffMeshLink(). How should I prevent it from recalculating the path?
My project has audio files that get generated in real time. Whats the best way to add the audio to an audio source while the project is running?
add component then assing clip and play
void Update()
{
ApplyGravity();
MoveForward();
Jump();
}
private void Jump()
{
if( Input.GetKeyDown(KeyCode.Space)&& IsGrounded())
{
_velocity.y += Mathf.Sqrt(_jumpHeight * -2.0f * _gravity*_gravityMultiplier);
}
}
private void ApplyGravity()
{
if (_velocity.y < 0 && IsGrounded())
{
_velocity.y = -2f;
}
else
{
_velocity.y += _gravity * Time.deltaTime;
_characterController.Move(_velocity *_gravityMultiplier* Time.deltaTime);
}
}
When my character executes the first couple jumps it sometimes lands right on the ground and sometimes below it. What is causing this?
Why is your CC radius and height so small?
Also from the code snippet you shared it seems you're calling Move multiple times per frame
CC behaves best with a single Move call per frame
How do I achieve this?
Simply add the two vectors you would have used for the two individual Move calls
And call it once on the sum
Could it be that my asset is too small and skin width is set to minimal as possible?
Ah all right
oh you mean move in apply gravity?
I mean one combined move call for both the vertical and horizontal motion
probably in ApplyGravity() I would just adjust the _velocity
likewise in MoveForward()
then elsewhere do the actual Move with the combined values
void Update()
{
ApplyGravity();
Move();
Jump();
}
private void Move()
{
_characterController.Move(transform.forward * Time.deltaTime * _moveSpeed);
_characterController.Move(_velocity * _gravityMultiplier * Time.deltaTime);
}
private void Jump()
{
if( Input.GetKeyDown(KeyCode.Space)&& IsGrounded())
{
_velocity.y += Mathf.Sqrt(_jumpHeight * -2.0f * _gravity*_gravityMultiplier);
}
}
private void ApplyGravity()
{
if (_velocity.y < 0 && IsGrounded())
{
_velocity.y = -2f;
}
else
{
_velocity.y += _gravity * Time.deltaTime;
}
}
I did this
Ah okay so you mean do the vertical and forward movement in one cc.move
e.g.
private void Move()
{
Vector3 horizontalVelocity = transform.forward * _moveSpeed;
Vector3 totalVelocity = _velocity + horizontalVelocity;
Vector3 totalMovementThisFrame = totalVelocity * Time.deltaTime;
_characterController.Move(totalMovementThisFrame);
}```
So I was moving twice per frame before
private void Move()
{
horizontalVelocity = transform.forward * _moveSpeed;
totalVelocity = _velocity + horizontalVelocity;
totalMovement = totalVelocity * Time.deltaTime;
_characterController.Move(totalMovement);
}
``` now Its like this
Uhm okay. Can you explain how this solved the "going below the ground" after jumps?
Was it that I was moving too fast to detect the collision?
Hey guys
I am new here
Hey can someone help me?
i have a Unity project more than 2GB, till now i used Git for version control but now git do not cover 2gb or more file size for version control in free plan
which version control do you guys use?
I'm thinking about how to implement stats for my units. i want them to have individual values x their jobs base stats. would it be a good idea to give the iv's and stat calcs on the units stat script and keep the base stats of jobs in a pure c# class?
Git .
you're probably not using .gitignore
Hello. I have a game that I need to Instantiate 500 objects of the same prefabs on start in random position (2D Sprites). What is the best optimization idea for this? I feel like doing for with 500 iretarions is bad idea
ScriptabaleObject (baseStats) -> POCO Class (copying and modified stats)
+1 on the gitignore problem, but I'd like to add that your .gitignore might not actually be working. I find this is usually because the project directory (Assets, Packages, etc.) are not in the same level as the .gitignore
yup, something to keep in mind
If they dont need to move then you can probably instantiate them while the scene loads and disable
computers can handle way more than 500 iterations
It's going to be a mobile game
1 per frame?
so here is detailed issue:
i used to work from macOS
i created a project there, worked on it for a month,
YES, do use gitignore. My .gitignore file code is exactly copied from the Git unity template for gitignore
it worked well till now when i was on MacOS
but i just purchased Windows yesterday and today when i do git clone with the link
it clone the project in local but here is the bug:
"ImportFBX failed" and i cannot see any mesh renderer
so make 1 SO for every units jobs base stats and switch those out for different jobs?
all my mesh renderer are missing
ALL PREFABS mesh missing and it is NOT PINK but white or transparent and missing
Can probably do this, I still recommend running the instantiation in a loading sequencce so the player doesn't see the freezing while they instantiate
could you elaborate?
load scene async, put loading screen
are you sure the repo was correctly uploaded?
I'm not sure if Awake methods are part of loadsceneasync, but if they are then instantiate in awake.
and when the scene loads and and all objects are instantiated then remove the loaiding screen with nice fade out
i dont know
i am noob honestly
how can i make sure of that though?
you can switch them out like assets yea, you just need them to copy the base stats, then use a regular class copy over if you want to modify the values
still, should i do it in a coroutine? async loading + coroutine 1 object per frame
never modify a SO for base stats
or async loading and 500 iteration for loop?
Coroutine would help if you'd like to eliminate freezing in the loading screen. If you're okay with the loading screen freezing then do it in a for loop.
for loop can just be thrown in the corotuine
Well, yes, but by for loop I mean straight synchronous
yes i know
im talking just pure for or for with yield return
Benchmark it out, see how many instantiations you can do per frame without freezing
i am capping my game framerate for mobile platform to 30fps, to if i am about to instantiate 500 objects that will take 500 frames approx
yea will do
thank you for the ideas
i commit and push again i guess and recheck my gitignore file
make sure you pushed with the gitignore committed
also i want to avoid spawning objects in the same position as my other object
any idea how to achieve that?
pick random position, do overlapbox2d and check if there is any object inside that box
if yes, repeat?
checkbox
if no, spawn?
or overlap sure
yea ok
Overlap would work yes
i wonder how will that be in optimization wise
By the way,
cuz i can see a sitaution where it's at 499 iteration and there is not much space
and its trying to find empty space al ot
All of the physics check methods are very fast by design
would not worry about such a thing early
okay
Quoting lordofduct off the unity forums here:
How Awake and Start is setup it's:
You call LoadLevelAsync (you may not have, this is step 0, because the game may have just been started and steps 1 and on still occur)
Load of scene occurs, objects get deserialized and created.
Once everything is created, Awake is called on all scripts. It is safe to grab references to other objects in scene, BUT those objects may or may not have had Awake called on them.
All enabled/active scripts have Start called on them. This is guaranteed to happen after ALL Awake calls. So intercommunication between scripts is cool.
If LoadLevelAsync, and you yielded the AsyncOperation, this will now return. As far as I can tell it's the frame FOLLOWING the 'Start' call on all the objects loaded.
So you can run all this in a loading screen, yes.
You shouldn't feel bad about using any of them as much as you need to, they are unilaterally faster than any sorts of alternatives
alr
idk if you have followed the context
Obviously doing nothing is better than doing anything, but the physics methods are designed to be used frequently
sidenote this is a thing that should be added to the documentation
if its not already
ow so i can do the initialization in awake then
if i understand correctly
Yeah, Awake or Start
cool, tysm
So I have ton of string contents in scriptable objects that are remote addressables. I need help with how to work with dynamic contents like this. I meant I've searched any localization tutorial but must of them just a simple tutorial like localization in the build. In my case these string contents is a CDN which is downloadable later by user. Someone enlighten me please!