#💻┃code-beginner
1 messages · Page 185 of 1
all of this happens in that line. you cannot wedge any code in between, and know that any code you write in the lines after Simulate() is AFTER all OnCollision… basically like LateFixedUpdate (if it were a thing)
just giving you info because the documentation does not have the details
it might as well say “run the physics simulation lol”
is there a way to check collision without using ontriggerenter2d and ontriggerexit2d?
like check immediate collision?
I'm trying to do a thing where I place a building only if it's not intersecting with another 2d collider
and have it be greyed out if it is intersecting
but for that I need a bool that's only true when no colliders are intersecting
and the enter and exit functions are not behaving as expected
nvm, figured it out. It's OverlapCollider()
Can someone explain this snippet to me? (Taken from the Unity documentation site)
I get that it creates a raycast 10 units forward from the GameObject
But how is it an If statement
And how does it detect that there's something in front of the object
this is the full thing
If the raycast hits something, it returns true. If the raycast does not hit anything, it returns false
So the if statement actually creates the raycast and listens for it returning true simulataneously?
I don't know what you mean by "creates the raycast"
I wouldn't say anything is "simultaneous" here
casts the ray
it's a bool type method
if (whatever) evaluates whatever
It is just checking if anything in that line
it's math
no objects are created or listened for
in this case, it evaluates Physics.Raycast(transform.position, fwd, 10)
If that expression evaluates to true, then it executes the following statement
it checks if the line with those properties intersects a collider, and returns true if it does
and if its evaluated as false it returns nothing?
It never "returns" anything.
it returns false
does it execute the next statement or not
In this case, since there's no else or else if, it just skips its statement and execution continues.
Does if (false) something; execute something
probably not
Do you know what if does
yeah i've just never used it in such an odd context
well, odd to me
i'm a beginner
usually my ifs actually listen for say... a trigger or two values syncing up or something
How is it odd? You put in a condition, and if that thing is true, it runs the code inside the if
ive never encountered an if statement that listens out for something like that
if (MethodThatReturnsABool())
Think of it like that
What do you mean "listens out"
It evaluates an expression.
bro im just wording it badly you know what i mean
it literally just checks a true or false
If the expression is true, it executes its statement.
fine, evaluates an expression, whatever
like always
That's all it does, ever.
if (x == 3) also evaluates an expression
alright alright i get it
if (true)
if (1 == 1)
if (3 < 5)
if (MethodThatReturnsTrue())
if (6 != 4)
I GET IT
if (someBoolean) also evaluates an expression
all of these will have the same outcome
All I need to know is, does the if statement evaluate the raycast returning true/false, and then executes the following statement if it returns true
Yeah?
As always.
An if statement checks if the thing inside the () is true. If it does, it runs the code in the if
Alright, thank you
There is nothing special here, and there's never something special here.
We are confused about why you're asking the question at all.
It suggests you misunderstand something.
Raycast is a method. It just returns true or false
The if statement doesn't evaluate the raycast itself, the raycast just returns
raycast is overloaded
actually this poses a new question
if the If Statement is evaluating the raycast, what actually casts the ray in the first place for it to be evaluated
But every overload returns bool
can return a bool or a raycasthit2D
Physics.Raycast
oh, idk about 3D
Raycast cannot return a raycastHit2D. Raycast2D cannot return a bool
you can't overload a return type
alright....
The code of the Method.
Again, the if statement is NOT evaluating the raycast
i think i get it
bro you're getting caught up in semantics here
2D raycast can return an int or RaycastHit2D
i'm just bad at phrasing this
you're asking a question about semantics
That function returns true if the line you define intersects a collider.
It returns false if the line you define does not intersect a collider.
That's it
okay anyway i got all i needed so thank you
bool MyMethod() {
return false;
}
if (MyMethod())
This is important, not getting caught up in it
why did they do it this way? idfk, but they did
2D Unity used to be an entirely separate program way back in the day
They did things slightly different
My guess? The 2D people didn't know out parameters existed
2D physics methods are strange. they populate arrays/lists that you feed in so they can do everything non-alloc. But they don’t pass them in as ref
There's NonAlloc methods for 3D as well
you don't need to pass them as ref
I am making a multiplayer game using Relay. Everything is working correctly and connecting fine, but I am having an issue with NetworkVariables.
For some reason, after my client joins the server, it does not retrieve the values such as the "LobbyCode" NetworkVariable nor does it retrieve the "LobbyNames" NetworkList.
The first image is where the problem occurs and both NetworkVariables are default when retrieved while the second image (Creating a lobby), the variables are set correctly. It's almost as if the client is setting the variables as default while the client should not have any write perms.
Any help would be greatly appreciated! (P.S. unsure if there is a channel specifically for multiplayer questions, I'm sorry if I am in the wrong spot)
that wouldn't really accomplish anything unless you wanted to completely overwrite the variable the user provides
isn’t ref the main way to indicate that a function is going to go modifying your input args?
at least in the context of lists and arrays
if that type was a value type. Arrays are reference types
It shares the actual variable.
right now, you’re just kind of expected to know that the input array is actually getting modified
public void MessWithList(ref List<int> theList) {
theList = new();
}
this assigns a new list into whatever variable was passed as an argument
vitally, this is nothing like just modifying the contents of the list you were given
public void MessWithList(List<int> theList) {
theList.Add(123);
}
correct, but how else do you indicate that your method is going to actively modify the contents of the collection?
by documenting it
ref should not be used for documentation purposes
the parameter name should make it obvious, and the method's documentation should also describe what it's going to do
//
ref does not mean "I might modify your reference type"
the non alloc methods are effectively taking in your variable and messing with it, as though they have a ref to it anyway
no, they do not
they mess with the thing you have a reference to
they don't touch your variable at all
true. I just find it strange to make methods that try to modify the input
every instance method is a method that modifies its input (:
input arguments
what is this but an implicit zeroth argument?
Not true, it's entirely possible to have a stateless method, one that could 100% be made static but for whatever reason is not
oh yeah, I should say every one could
C# gets mad if you call a static method from an instance..
C# has no equivalent to c++'s const qualifier on methods
which promise that the method has no effect on the instance
This is my script for accelerating my rocket:
void MyInput()
{
if(Input.GetKey(KeyCode.LeftShift))
{
accelerating = true;
}
else {
accelerating = false;
}
if (accelerating)
{
if (moveSpeed !< maxSpeed)
{
Debug.Log("Accelerating!!");
moveSpeed *= 1.001f;
}
}
else {
moveSpeed = moveSpeed / 1.02f;
}
}
Later, I add a force by:
if(accelerating)
{
rb.AddForce(Vector3.up * moveSpeed * Time.deltaTime, ForceMode.Force);
}
However, when I press LeftShift the moveSpeed variable doesn't increase. When I remove the
else {
moveSpeed = moveSpeed / 1.02f;
}
part it works. Any idea why?
!< does not do what you think it does
you've actually written moveSpeed! < maxSpeed
although I guess that's technically fine here
!< 🤔 is different than you think . . .
you probably just wanted moveSpeed < maxSpeed
Structs got that, you can put a readonly modifier on a method! Not sure which version this was introduced in though
I have it on a get accessor, actually..
Ah, there it is!
If you want "not less than," that is called "greater than" . . .
Oh gosh im stupid haha
Thank you!
That shouldn't change anything, though
! is the null-forgiving operator, which isn't going to do anything here
Well it works now :3
Perhaps you had that else { moveSpeed = moveSpeed / 1.02f } in the wrong place before.
Hi guys. Beginner question: Why is this code not showing up in the inspector of the object:
public float BulletSpeed { get; set; }
if i leave { get; set; } away it will show up
[SerializeField]
public float BulletSpeed { get; set; }
Wont work either unfort
because properties are not, by default, serializable
public float BulletSpeed; declares a field.
use the correct attribute
[field:SerializeField]
Ok that works. Whats the difference between these two:
A:
[field: SerializeField]
public float BulletSpeed { get; set; }
B:
[SerializeField]
private float BulletSpeed;
public float BulletSpeed { get; set; } declares a property with auto-implemented properties
properties "look and feel" like fields, but a method is called when you read or write them
thank you very much for the links very helpful 🙂
man, you need to learn some basic c#
auto-implemented properties create a backing field that stores the value
comming from javascript you are most likely right 😄
hence needing to specifically target the backing field with [field: ...]
otherwise your attribute targets the property
but now that it works and its my kinda first steps with OOP im kinda proud of this:
abstract class Weapon : MonoBehaviour
{
void Start()
{
Debug.Log("Start");
Shoot();
}
[SerializeField]
public float Damage;
[field: SerializeField]
private float BulletSpeed { get; set; }
public GameObject BulletPrefab { get; }
public float Cooldown { get; set; }
public abstract void SetupShot();
public virtual IEnumerator Shoot()
{
while (true)
{
SetupShot();
yield return new WaitForSeconds(Cooldown);
}
}
}
feels so good man 😄
that aint gonna work
You are right:
class SimpleGun : Weapon
{
public override void SetupShot()
{
Debug.Log("Shoot simple gun");
}
}
This wont get logged at all
Shoot is a Coroutine, you cannot call a coroutine with Shoot()
how to do reverse of %
o\o
to count how many of certain number fit in certain number
you mean Min()
division?
that's just division
full digit division
division, then floor
still not sure what he wants
fine, thought of cheaper function
abstract class Weapon : MonoBehaviour
{
void Start()
{
Debug.Log("Start");
StartCoroutine(Shoot());
}
[SerializeField]
public float Damage;
[field: SerializeField]
private float BulletSpeed { get; set; }
public GameObject BulletPrefab { get; }
public float Cooldown { get; set; } = 1f;
public abstract void SetupShot();
private IEnumerator Shoot()
{
while (true)
{
SetupShot();
yield return new WaitForSeconds(Cooldown);
}
}
}
This now works.
Now it #feelsgoodman 😄
this
[field: SerializeField]
private float BulletSpeed { get; set; }
public float Cooldown { get; set; } = 1f;
is completely pointless
[SerializeField]
private float BulletSpeed;
public float Cooldown = 1f;
does the job correctly
the only reason to use a property there is if you want children to be able to override it
but then...
- it'd need to be
virtual - there'd be no point in serializing it
I suppose that children that don't override it could just leave it untouched, which would give you a serialized value for it
Yep i get it now. I had it kinda like this because i wanted to understand why with getter and setter it wont show up in inspector. But now that I get.
i want you guys to double-check this to make sure im understanding correctly
if (Physics.Raycast(myRay, out RaycastHit hit, maxDistance, layersToHit))
// myRay - Specifies the raycast that should be involved in the If Statement.
// out - Output: Creates a new method parameter, specifying that it returns an additional value on top of the method's default return values.
// RaycastHit hit - Creates a RaycastHit variable called "hit" (In order to store the collision data)
// maxDistance - Specifies how far away from the Raycast origin that the If Statement should apply for.
// layersToHit - Specifies which layers the raycast should interact with.
None of this has anything to do with the if statement
Physics.Raycast(myRay, out RaycastHit hit, maxDistance, layersToHit)
This calls Physics.Raycast with the provided arguments.
but are my definitions of the "provided arguments" correct?
am i understanding it all correctly
remember that terms such as "out" and "RaycastHit" are new to me
i need to know that my understanding of the arguments is sound
if it isnt correct me
ignoring the thing about if, yes, it's reasonable
out is a keyword that passes an argument by reference so that the method can assign something into it.
and since you're using out, you're allowed to declare a new variable right as you use it
myRay is not a Raycast, It's a ray
out is a C# term that specifies a new variable that will be created by the function and given as output
The rest is fine
rather than using a variable you declared earlier
RaycastHit hit;
Physics.Raycast(myRay, out hit, maxDistance, layersToHit);
Physics.Raycast(myRay, out RaycastHit hit, maxDistance, layersToHit);
Same outcome.
Thank you.
wait just a second. GC?
I see no reason for that to come up here.
Both get GC'd, just at different times, belonging to different scopes
RaycastHit is a struct anyway
yes, which can make one hell of a difference
also, they live in the same scope
I think the one declared inside the function exists inside the if scope (if there is one)
if (Whatever(out var foo))
{
}
print(foo); // foo is still here
Ah, then they're the same
no it is not
yes it is. you can try it yourself
if (!target.TryGetModule<Visible>(out var visible))
continue;
float angle = Vector3.Angle(forward, visible.entity.transform.position - from);
random example
That is how I do it all over my codebase
It is lost after the NEXT scope end, but it exists outside the if statement for sure, as you said
lexical scoping rules apply as per usual
a somewhat ambiguous-looking case gets resolved by a compiler error
if (true)
int x = 3; // error CS1023
the compiler just forbids declarations here
I didn't actually know that. I'd never thought it might exist outside the scope so any time I needed to I just defined the variable outside the if
Neat
It'd be a chicken and egg problem
the variable must exist to evaluate the if expression, but it can't exist until you enter the block statement
Not really a code problem. Try #💻┃unity-talk
kk
Pretty sure the 2nd one would be compiled to the first one anyways
sugar in the eyes of an angry compiler
How can I make this
[SerializeField]
protected Transform ShoootingPos;
To be by default the transform of the gameobject the script is attached to? Kinda like make it optional?
the most practical thing is to just assign something in Awake
if ShootingPos is null, assign your own transform to it
so basically check if its null? and then assign?
yes
ok thx 🙂
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.layer!= _playerMask) return;
GameController.Instance.Score++;
if (_audioClip != null)
{
// Play the audio clip at the specified position
AudioSource.PlayClipAtPoint(_audioClip, transform.position);
}
Destroy(gameObject);
}```
When I change this from Compare tag to layer it stops working?
I mean its working but its not detecting player
- why do you need to check the layer in the first place?
- the layer property is not a mask
You seem to be comparing a layer to a layermask
why do you need to check the layer in the first place? why not go back to using a tag?
Someone said to check for layers
You can check that the layermask contains that layer. But yeah, I dunno if this is the best way
okey will go back to tag
I listed layers as a method of collision validation, but it was the last of three suggestions. And I more meant using the collision matrix to reduce collisions you have to check
I dont understand how collision matrix setting works
Ignore it
Just do tags
Yeah I just reverted to tags
If you need more complex functionality, also check if a component is on the object using TryGetComponent
I have this at some places
for future reference though, this is how layermasks work and what they are https://unity.huh.how/bitmasks
again though, it is not necessary here.
But mostly its not needed due to most of my scripts positioned on the object of interest
Yeah I know how access layermasks
I got told something about this
This
Seen the setting
And understood nothing
And recently I done few changes to remove lots of GameObject.Find and still dealing with aftermath
You just put a checkmark where you want collisions to occur. If there is not a check where two layers line up, they will not collide
collide like fisical collide or trigger?
Oh then im going to edit that and see what happens
its just build takes at this point a minute
does anyone know why this is happening? i'm following the sebastian graves tutorial for dark souls and my camera just shoots away from following the player. when i move the player the camera still moves. but why is it like this?
you'd have to show relevant !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 which one? the camerahandler?
If it is relevant, sure
They told you how to post code above #💻┃code-beginner message
Either use a paste service to post large code blocks or inline code if it isn't too large.
!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.
Hello, how can I get the normal direction of a face ?
Define face. A plane would have the normal property.
Like have a checkbox for what my character is on, but I'd like to get also the normal direction info
define normal direction info
Yes exaclty like the normal of a face from a mesh
If the "face" is a plane, it should have the normal property else using some math logic, you'd be able to get the normal of the plane given two vectors https://docs.unity3d.com/ScriptReference/Vector3.Cross.html
so do i post ot on one of these sites? then what?
How do I change the color of the collided GameObject back to it's default if it's not being raycasted onto?
else
yeah but I mean what's gonna be in the else statement
The site should have a save button somewhere on the screen. The URL will change after saving and you'd post the url here.
just else return or some shi?
assignement to the default color
this is a pretty common question
you need to remember the last thing you hit
And quickly how can I get the plane I'm standing on ?
then, if your raycast either:
- hits something else
- misses entirely
you can reset the color of the last thing you hit
How do you know there's a face under you?
You can store the last Renderer that you changed the color of and then compare that against the Renderer that you just found
how do i do that
store the Renderer in a field so that you can access it later
what about the comparison part
just compare them with the == operator
or maybe !=, since we want to do something when they differ
Rather how I get its information. I have a checkbox, and the is there a method the get the touched pkane information ?
if (oldRenderer != newRenderer) {
if (oldRenderer != null)
oldRenderer.color = ...
if (newRenderer != null)
newRenderer.color = ...
}
oldRenderer = newRenderer;
that's the broad idea
that doesn't look like a real word anymore
why null check after checking it to new renderer?
is there a way to automatically find the color so i don't have to manually input it in, for example if there was different colored objects
because the new renderer could be null
store the color as well as the renderer
first check if they are null then contine?
e.g. if your raycast hits something with no renderer
alr
Even if the new renderer is null, we still might need to reset the old renderer's color
if the old renderer isn't also null
old renderer <-- not null
new renderer <-- null
this means we just went from pointing at a renderer to not pointing at a renderer
you'd get newRenderer a bit like this
Renderer newRenderer = null;
if (Physics.Raycast(...)) {
newRenderer = hit.collider.GetComponent<Renderer>();
}
if the raycast whiffs, it's definitely null
Consider using one of the physics casts
- 2D: https://docs.unity3d.com/ScriptReference/Physics2D.html
- 3D: https://docs.unity3d.com/ScriptReference/Physics.html
Under the static methods section
if the raycast hits, then it might become non-null, assuming the thing we hit has a renderer
Gonna check this out, thank you !
How can I set up a scoreboard for my enemies? They seem to be destroyed because I can do anything with them
The only fix I have in my head is having them pull the game controllers script on start so that on collision with a bullet, they add to the controllers score
what will this scoreboard do?
is it tracking each enemy's score?
or is it tracking how many points the player has?
that is a fine way
Just shows players score
issue comes if you have multiple levels
okay, so the enemy needs to notify someone when they get destroyed
Every object (via Transform component) would have a forward and up. That would be two vector and define the orientation of the object. Forward would be the normal for a 3d surface btw. If you're wanting the normal for a 2d object, it'll require a bit more math.
You need DDOL object to store score to pass it between levels
The controller isn't destroyed on load to save my stats
The only fix I have in my head is having them pull the game controllers script on start
Whoever instantaites the enemy should pass them a reference to the controller, yeah
just save score in controller and make it singelton and access it to get score if u need it elsewhere
{
RaycastHit hit;
for (int i = 0; i < rayCount; i++)
{
float angle = i * 360f / rayCount;
Vector3 direction = Quaternion.AngleAxis(angle, Vector3.up) * transform.forward;
if (Physics.Raycast(transform.position, direction, out hit, detectionRadius, _raycastLayerMask))
{
Debug.DrawRay(transform.position, direction * detectionRadius, Color.green);
Debug.Log("Hit: " + hit.collider.gameObject.name);
if (hit.collider.CompareTag("Player"))
{
float distance = Vector3.Distance(transform.position, hit.point);
Debug.Log("Distance to player: " + distance);
if (distance < 2f)
{
_canChase = false;
SetState(State.Attacking);
PlayerController.instance.boxColliderTrigger.enabled = false;
}
else if (distance > 3.5)
{
_canChase = true;
SetState(State.Running);
PlayerController.instance.boxColliderTrigger.enabled = true;
}
break;
}
}
else
{
Debug.DrawRay(transform.position, direction * detectionRadius, Color.red);
}
}
}``` i am inside the radius and the player has the player layer on it but not one debug is called
I looked at the links you set, my strategy will be to get a raycast hit normal, at least that what seems the esasiest for me
I have no idea how to access the score if there is a more normal way
So grab the scoreboard with the player on start and pass it onto the instantiated bullets?
!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.
Only if shooting enemies is, itself, worth points, IMO
but I guess it would be a good way to indicate who shot the enemy. That'd matter if enemies could shoot each other without giving you points
https://hatebin.com/kvheyytnba
This is my GameController class.
private void OnTriggerEnter2D(Collider2D other)
{
if (!other.CompareTag("Player")) return;
GameController.Instance.Score++;
if (_audioClip != null)
{
// Play the audio clip at the specified position
AudioSource.PlayClipAtPoint(_audioClip, transform.position);
}
Destroy(gameObject);
}```
This is my gem class that I use to get score
When the enemies due, they should give points, and mostly are 1 shot (minus the boss)
As you see I access score by accesing Instance that is static
Wait is an instance what the clones are?
instance is the unique instance of that class
Almost finished I am but Domain starts to take a minute to get anything done
Instance is a reference to itself. It is static so it can be accessed from anywhere.
Otherwise you will make new instance of the class each time you want to acess a value and will need to make all those values static too
Well, reference. You could keep the same instance.
Unless I'm missing some context?
Well if I know C# well enough only way you can pass same instance of class without static is by directly passing it
You will basically have a tree of references
Wait so which instance is this pulling, a bullet or an enemy?
Its a controller object
Basically true... some nuance is missing
I have it dealing with Scene changes, storage, spawn on points etc
I have it control the spawn because of what I spawn
Also probably will spawn the portal from start because it causes a lag spike
i solved the problem, i saw how my structure was flawed and i solved it, this is how it is now for nayone wondering
that "this" is irrelevant
this exists to differentiate variables from class and method that have same name
The only code that actually runs here is Awake. Is there another script that calls the other methods?
https://hatebin.com/jjlmgairnl
there's this. the InputHandler script that i got from the same tutorial
Instead of public transform reccomend using [SerializeField] private
Also most of these can be achivmed with transform or gameobject references
you have nothing running on FixedUpdate or Update so this code runs once and only Awake part
So ig I also have question 2, to pass the level, I had this (possibly ridiculous idea) of setting spawner references to the game object that added a counter for my enemies, basically they all spawn until +20 are created before quitting, and they then deactivate themselves, as all the spawners and enemies would have a trigger with the background so that the game knows when they are all dead since the game won't unlock level 2 until
First- all enemies are spawned and the spawners are done
And secondly, all the enemies are dead allowing the level 2 gate to open
how do i fix it?
Yeesh that's more than I thought
add void Update() (This runs every frame)
Or void FixedUpdate (runs every set time, dont know well but movements should go here)
Also you can use cinemamachine to make camera go after someone
which line do i add void Update()
They have FixedUpdate already
Eh, reworded would be I'm confused on how to make an enemy detection system bc I was told that finding an object with a certain tag was laggy
Line 22
you can serialize field and set that object
No, that script is controlled by the other
The second script has the fixed update
laggy is constantly searching for it
ah then no need
if you search for it once in a scene its not end of the world
Is MoveInput supposed to be a callback? That isn't called anywhere I see
It needs to find it until all are dead
I just don't know how to prevent it from breaking when it no longer finds an object
why just not make an empty object that holds all enemies and serialize this then just count how many children it has?
The enemies are instantiated
add them to that object as children
Basically most of commands that are not GameObject.Find() are not really coputation heavy at least at beguinner levels
i'm not sure. i was just following the tutorial
So running a fixed update find for a tag wouldn't be to strenuous?
What exactly are you trying to achieve? And for what reason does it need to find them if you instantiate them and therefore already have a reference to them?
also that
tho reference not gonna be of much use
unity wont automatically set object as null
Didn't read everything so I don't know the exact context
you can tho save amount of created enemies into variable in DDOL class with public variable and minus the dead ones
I need a way to know how many enemies were spawned, or at minimum, to make sure that all enemies are killed before the game is allowed to move on to level 2
when you inicialize enemy add 1 to a variable in gamecontroller class
when it dies just minus 1 from there
and when it reaches 0 you can just load next level
Why not then just have a counter which increases with each enemy spawned, and decreases with each enemy killed?
I understand that, I'm not sure how to remove them
just do same as adding them
instead of ++ do --
If health is not going to start working soon my brains gonna melt
It's not the same though, the spawners aren't going to keep track if their spawned unit was killed
they dont need to
how do you kill an enemy?
just access the variable from there
it doesnt matter from where what matters is the count
The bullet collides but in doing so, destroys itself before sending back the object it hit
If you're not sure, you need to go back and follow the tutorial again until you know.
Sebastian Lague tutorials are a bit higher level, and considering you asked which line Update should go on, I think you may need to go and do some more basic tutorials first.
Have you gone through the Unity pathways yet? That should be the first thing you do
👇
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
before it commits sepucu just add a line that acces variable like this
GameController.Instance.EnemyCount--;
literally it matters not
Either access the variable from within the enemy, or make an OnEnemyDeath event for the counter to subscribe to, or pass a delegate to invoke upon death
So give the bullet a reference to the count on start, and allow it to -- it before it goes poof?
You dont need reference
Just call it when its killings something
this is pros of singleton class
Then how would it know that a count even exists?
It does not needs to
Literally just
if(hitenemy)
SingletonClass.Instance.Count--;
CommitDieOther
CommitDieMe
when you create an enemy just do this
Instantate(enemy)
SingletonClass.Instance.Count++
Hold up, are all of my variables singletons?
I feel like I use public static alot
Just looked up singletons bc I've never heard the term before
Here's a delegate solution of how you could do it.
public class Spawner : MonoBehaviour {
[SerializeField] Enemy m_enemyPrefab;
private int m_counter;
public void Spawn() {
++m_counter;
Instantiate(m_enemyPrefab).Init(OnEnemyDeath);
}
public void OnEnemyDeath() {
if (--m_counter == 0) {
// Unlock level
}
}
}
public class Enemy : MonoBehaviour {
private Action m_onDeath;
public void Init(Action onDeath) {
m_onDeath = onDeath;
}
public void Kill()
{
m_onDeath?.Invoke();
Destroy(gameObject);
}
}
Using events is also a good solution I suppose
Objects have an on death action?
can someone help me with visual studio? I've downloaded the unity game dev download but every C# file that I open from unity gets this miscellaneous files assembly instead of the csharp one and I cant find a way to change it
yeah thy do
!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
OnDestroy()
Thanks
i am following the tutorial annd everytime i put the player model in the target transform slot. the camera moves right infront or below them
its probably because it also takes camera position values before
at least in tutorial I seen before that was an issue
i've zero'd each of them like 5 times and it still doesn't work
you put in the Scene object not prefab?
regardless of whichever one i do it does the same thing
Im way to tired atm. Have u posted the code?
yes it's above
https://hatebin.com/ejuytvpqdh
This urs?
yes
you know in games where you place a building and the unplaced building hovers over your cursor until you click
I'm doing that, and the following code is supposed to make the unplaced cursor building snap to the grid cell that it's over
Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cell_coords = gs.tilemap.WorldToCell(cursorPos);
transform.position = gs.tilemap.CellToWorld(cell_coords);
the problem is, there's some kind of offset
the final transform position that gets set is wrong and ends up misaligned with the grid
I'm worried it's related to the fact that grid cells have their transform.position point in the top left
and the building has it in the center
@earnest atlas @modest dust thanks for your help fellas
is that logic?
if the player trigger the canon
it will start the update
then the update will wait until the shoot is ended and it will repeat?
right?
Update runs every frame, which means the IsCoolDown coroutine starts once per frame.
In OnTriggerEnter, if this collides with something tagged player, it'll start a coroutine. This coroutine will check if the F key was pressed this frame. If it does, it does a bunch of stuff including a wait of 1.25f. If the key was not pressed this frame, the coroutine waits 4 seconds, does nothing, then ends
why are you calling starcorroutine in update
won't that create a new coroutine every single frame?
It does
why would you want that
They probably don't and simply do not understand how coroutines work
oh gotcha
@clear seal update doesn't need to be triggered
it'll call constantly as often as it can
but then how do i make it work?
so you just want it to shoot if it's off cooldown and not shoot if it's on cooldown?
yep
you can use coroutines for that, but I find it's typically simpler to just use a timer
lemme give an example
public float cooldownTime = 1f;
private float cooldownTimer = 0f;
void Update()
{
if (cooldownTimer > 0)
{
cooldownTimer -= Time.deltaTime;
if (cooldownTimer < 0)
cooldownTimer = 0;
}
if (Input.GetKeyDown(KeyCode.F) && cooldownTimer <= 0)
{
Shoot();
cooldownTimer = cooldownTime;
}
}
void Shoot()
{
// shoot code goes here
}
If you want to use coroutines it's a simple matter of setting a bool to false, then starting a coroutine that has a wait, then sets that bool to true
are the codes written in junior programmer unity courses well optimized codes or are they like the codes from beginner youtube tutorials that are poorly written for people to understand easier
if it's true, you can shoot
actually that probably is a bit simpler
since waitforseconds does this same thing in one line
Remember that Coroutines are Co routines. They run alongside the rest of the code. Nothing will wait for a coroutine to finish, so having the last line of a coroutine be a wait is 1000% pointless
void Update()
{
if (Input.GetKeyDown(KeyCode.F) && canShoot)
{
StartCoroutine(ShootWithCooldown());
}
}
IEnumerator ShootWithCooldown()
{
canShoot = false;
Shoot();
yield return new WaitForSeconds(cooldownTime);
canShoot = true;
}
Phone coding is too slow again. Almost had it done haha
Do it like that goldwerdz☝️
anyone know a workaround for this?
I'm pretty sure it's the pivot, but it could be something with the CellToWorld function rounding or some nonsense like that
the only thing that makes me think it's not the pivot is that I tried with a gameobject that has a transform instead of a recttransform and it's still off
Hey guys, I wrote a script EnemyController (https://gdl.space/inijebuyap.cs) and within it there exists the ShootBullet method. This method instantiates a bullet (BulletScript: https://gdl.space/fikoluxawa.cs) and sets it's moveDirection based off which direction the Enemy is facing. This works fine when there's only one instance of an Enemy, but when there are more (and are both facing the player from different sides), they both start shooting in the wrong direction.
Do you have an example of code from that course you are concerned about? Also can you elaborate on what you mean by "optimized"? Usually there are many ways to solve a problem, and later on architecture can play a role in helping with that too, though optimizing usually suggests a concern with performance such as low framerate, memory management, rendering draw calls, etc, unless your referring to something else?
Are we talking about 2d or 3d here?
this is 2d
And the camera is set to orthographic and has 0 rotation?
correct
I heard in a youtube video that he says you shouldnt watch these beginner tutorials on youtube because they make you learn coding part poorly so in the future when you make a game you can face lots of problems
so i try to learn it right from the start
so is unity junior programmer a good place for this?
Thing is, you're not supposed to stay on the level you learn as a beginner.
Your knowledge/understanding and coding skills in general are supposed to improve over time.
It's fine to write unoptimized code and use bad practices at first, but you'll learn better coding with time and experience.
Learning from mistakes is importance. Learning what others tell you is right from the beginning actually hinders you imo
The flip side is that you need to strive to learn and not let bad habits become ingrained
The problem with the tutorials is that they give you partial understanding for the sake of achieving a specific mechanic or even plain out hand you the implementation on the plate without you actually learning anything in the process
That's why a systematic course like the unity pathway one is better.
you mean call shoot = true and then false?
canShoot is a bool that you can use to check if the cooldown is up or not
exactly
in the coroutine, it'll be set to false after you shoot, then the coroutine waits for the cooldown, then it sets it to true
why would it be set to true if it's ended
the coroutine doesn't end like a normal function
how come
it will continue running in the background until the waitforseconds is done
the whole point of coroutines is that they don't end, they wait in the background for something
and then once that happens, they can end
but the rest of your code still runs while the coroutine is waiting
but from what i have understood is
can shoot false => shoot => wait => can shoot true right?
yeah that's the flow control
and notably the other functions like update are continuously being called while wait is happening
in game engines, there's something called frames
ok
it's kinda like a clock that ticks every second
ok
except a frame usually ticks like 30 or 60 times per second
based on how fast your computer can run code
it varies
every time a tick happens, unity will call the Update() funcition, and any code you put in update will run
ok
so that's why we put the code that checks if you hit the f key and then shoots in update, so it's checking as fast as it can for whether you pressed it
ok
typically, code can only do one thing at a time. it runs each line of code in order. this creates a problem, because if we want it to wait 10 seconds, it will have like 600 frames where it's not running any code and your game will just be frozen
ok
so there's two ways to get around this problem. the first is just to write down the time that has passed in update and only allow the player to fire if the time that has passed since we started writing it down is bigger than 10 secs
that's what I was doing here
just writing down how much time has passed by subtracting from the cooldown how much time has passed since the last tick
hold i will be back just going to unity deltatime learn video
ok
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I did this, and it seems to point exactly where the cursor is, which is not where the gameObject is ending up
can someone help me with vscode
@teal viper@summer stumpthanks. thanks to you I finally feel relieved following something about learning coding on internet 🙂 (as someone who followed youtube tutorials for 3 months when I was using gamemaker and I couldnt do anything after the tutorials)
!vscode
Whenever I try to run a specific file it just runs the last file I opened before that file
it kinda sorta isn't involving unity
What do you mean by that?
it told me that it couldn't run a java file I wrote so it just runs the most recently opened file besides for that file
now I can't fix it
I guess I'm confused by the term "run" here. But I don't use VSCode so I dunno
Okay. What object does the script belong to? Can you take a screenshot of it's inspector?
I opened a dice simulator file before this file so it keeps running the dice simulator instead of the file I have open
it's got a rect transform because it's attached to the canvas, and i thought that might be the problem
but I remade the gameobject from scratch as a regular gameobject
and the same exact thing happens
Have you quit the dice rolling program or closed the shell?
both
if I open a different file then it will use that one
Then it's probably the position of the cell.
Well I dunno. But since this is not a Unity issue, I don't think I can continue with the off-topic. Sorry
fair enough. thanks for the help
Can you draw a ray at the cell world position?
i hid this but now i cant seem to get this back up (had to find a yt vid to show this) where can i turn this back on?
dont bother thinking of that i was too lazy to erase it
can you copy paste this as text? it's hard to read as a screenshot
how do i put colors
!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.
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public float bulletSpeed = 100;
private bool IsCoolingDown = false;
public AudioSource CanonShot;
public ParticleSystem CanonMuzzleFlash;
public float cooldownTime = 1f;
private float cooldownTimer = 0f;
void Update()
{
if (cooldownTimer > 0)
{
cooldownTimer -= Time.deltaTime;
if (cooldownTimer < 0)
cooldownTimer = 0;
}
if (Input.GetKeyDown(KeyCode.F) && cooldownTimer <= 0)
{
Shoot();
cooldownTimer = cooldownTime;
}
}
/**void OnTriggerEnter(Collider Player)
{
if (Player.tag == "Player")
{
Debug.Log("canon shot");
StartCoroutine(Shoot());
}
}**/
/**IEnumerator Shoot()
{
if (Input.GetKeyDown(KeyCode.F))
{
IsCoolingDown = false;
yield return new WaitForSeconds(1.25f);
CanonShot.Play();
CanonMuzzleFlash.Play();
Vector3 shootD = (bulletSpawnPoint.forward + bulletSpawnPoint.up * 2).normalized;
var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().AddForce(shootD * bulletSpeed, ForceMode.Impulse);
Debug.Log("coroutine executed");
IsCoolingDown = true;
}
yield return new WaitForSeconds(4);
}**/
void Shoot()
{
//yield return new WaitForSeconds(1.25f);
CanonShot.Play();
CanonMuzzleFlash.Play();
Vector3 shootD = (bulletSpawnPoint.forward + bulletSpawnPoint.up * 2).normalized;
var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().AddForce(shootD * bulletSpeed, ForceMode.Impulse);
Debug.Log("coroutine executed");
}```
To get the colors, you write cs after the first backticks
that looks right
this could be an else:
if (cooldownTimer < 0)
but that's just style
it should function properly
the other way to do this is with the coroutines
does this
work?
the way i did?
I find using timers to be more beginner friendly because you can see what the code is doing
but the community prefers coroutines, probably because too many cooldown timer variables can clutter up your code and make it confusing to read
thank god i have been struggling with coroutines for a week now
Anyone got any piece of advice for moving along normals? I'm trying to make a character that can move around a vertical loop, it works all good until he reaches the part of the loop that sticks vertically upwards, then he starts moving downwards; it happens even with no gravity so my best assumption is that it has something to with how the velocity is being applied to the rigidbody,
currently, I multiply the left and forward velocity by the transform.rotation.
The only things I do with the transform rotation is rotating it so that it sticks upwards following the normal of the ground using Quaternion.LookRotation.
and i forgot what was the goal 💀 😭
I didn't understand coroutines until I took a cs course that taught me about threading
basically the concept that computers can only do one thing at a time
Here's an example
and coroutines are a special workaround to get around that limitation
so it's effectively like multiple computers are running side by side in your computer
do you have the link for the courses?
it was a course I took in my college on java programming
but if you look on the internet about threading I'm sure there are good explanations somewhere
i also take courses but paid one and yeah
I drew a sphere at the location of the world coords of the tile
and as you can see, it's super offset
reposting my question cause I'm still super confused:
you know in games where you place a building and the unplaced building hovers over your cursor until you click
I'm doing that, and the following code is supposed to make the unplaced cursor building snap to the grid cell that it's over
Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cell_coords = gs.tilemap.WorldToCell(cursorPos);
transform.position = gs.tilemap.CellToWorld(cell_coords);
the problem is, there's some kind of offset
the final transform position that gets set is wrong and ends up misaligned with the grid
the sphere in the center of the farm should be in the top left of the grid cell I'm pretty sure
and for some reason the CellToWorld function is spitting out coords that make no sense
oh nvm, i fixed it
it was a combination of the tilemap being offset from the parent grid and the rect transform having the pivot in the center
the two bugs teamed up and made it take way longer to solve
is setting a game object through a public variable in the ui faster than transform.Find()? or is there no difference at all. i imagine it would be
Setting reference is mush faster than find
Assigning in the inspector is by far more efficient in terms of speed. GameObject.Find loops through all existing GameObjects and compares their names. Persisted direct links are basically free and initialized when the scene is loaded. Said that, direct assignments have a couple of draw-backs: You need to remember to assign them, which can b...
okay thats what i thought. i wasnt sure since it was done through the ui idk why i thought it might be slower lol thanks
Significantly
dc.rotateDuck(new Vector3(FirstPersonController.Instance.transform.position.x, dc.transform.position.y, FirstPersonController.Instance.transform.position.z) - dc.transform.position);
This may sound like a stupid question but I can't figure it out for some reason. This piece of code rotates the enemy towards the player. How would I rotate it away?
public void rotateDuck(Vector3 direction)
{
Quaternion rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Lerp(transform.rotation, rotation, rotateSpeed * Time.deltaTime);
}
This is how it rotates ^^
Should be fine to just swap the operation so you do dc.transform.position - everything else
Also your lerp isnt really a lerp, you may want to use RotateTowards or whatever the name is
What do you mena the lerp isnt really a lerp?
Lerp = linear interpolation. T should be a value going from 0 to 1, while yours is just a constant (simplifying here since deltaTime is not a constant itself). The value is going to relatively be very small but let's say around speed * 0.01f at all times.
You want to use RotateTowards because you can have it rotate at an exact speed, while not overshooting.
With your lerp, you cannot guarantee it will move at a certain speed. If the difference between A and B is larger, it will rotate faster
Oh alright so like this instead?
transform.rotation = Quaternion.LookRotation(newDirection);```
I was referring to the quaternion method
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
It's possible to do with vector3 but then you have to construct the quaternion afterwards anyways
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotateSpeed);```
so like this?
I have to convert the vector3 of the direction to a quaternion anyway
You still keep the rotate speed * deltaTime but yea looks correct to me. This should rotate an exact amount per second
I think it's all working good now, it just rotates a lot slower now so I've bumped up the rotateSpeed value quite significantly
I think the 3rd parameter is in degrees, so a value of 90 would be 1/4th of a full circle every second. 360 would be 1 full circle per second
Correct.
it causes framerate-dependent behavior
Ahh so if i made the speed value 180 it would take 2 seconds to rotate 360 degrees
Yes, should be easy to observe this happening if you setup a quick test. I'd test with 180 degrees because 360 would be the same position
Thanks for your help :), everything is working as intended now
Setting it through the ui or even a static class/singleton wouldnt be a barrier for speed, since a reference is stored in memory you always have direct access to it, whereas any "Find" call has to search a collection (your scene hierarchy for example) and check "is this index the thing your looking for?", (hopefully) eventually find the object and then return it, assuming you cache the reference after its found, then the speed difference would more-or-less be the same, but a direct reference in the UI means the initial search never needs to happen anyway
yo
when inside of a script how do you referance the game object the script is a child of
the transform property gives you your parent
and you can ask for the gameObject property from that Transform
alright
where should i start looking
to make an overlay that is locked to the camera
use a screen space overlay canvas
can you elaborate
actually now that im thinking about it i would rather have the text dialogues appear infront of the npcs
is there a gameobject that contains text
you could also just tell me
but sure ill go spend 15 minutes googling and finding unhelpful information until im lucky enough to stumble apon something i can use
nvm
if it takes you 15 minutes to find any information about how to display text in unity then you really need to get better at using google. this discord is not a substitute for learning or using google, it is a supplement
i just noticed the "legacy" in the ui thing which should solve my issues
This also isnt a code question
How do you code audio into your game?
I'm assuming the audio components need something to let them work
wdym by "need something"? they can JustWork™️
I can just add the file and they'll work when the game starts?
Alr, and how do you destroy an object (a gamecontroller) after its been set to don't destroy on load?
pass it to the Destroy method
Sweet
why i cant drag Text UI to Code?
probably because its TextMeshPro and you have Text
using UnityEngine;
using UnityEngine.UI;
public class ButtonTextChanger : MonoBehaviour
{
public Text textUI;
public string newText = "New Text";
void Start()
{
if (textUI == null)
{
Debug.LogError("Text UI is not assigned!");
}
}
public void OnButtonClick()
{
if (textUI != null)
{
textUI.text = newText;
}
else
{
Debug.LogError("Text UI is not assigned!");
}
}
}
Not sure why you showed the code.
Show the inspector of what you tried to drag in
If it is TextMeshPro, add
using TMPro
to the top of that script, and change the type from Text to TMP_Text

cuz it not my code
i just told chat to make code that when im click button just change Text on Text

You should absolutely not be using AI at this stage of your learning
But either way, you can show us what we need to confirm the issue, or continue on with whatever you want
im not good about code
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
it my project that i wanna create game
and almost over now
sry about that
but i dont have time
ty
"But either way, you can show us what we need to confirm the issue, or continue on with whatever you want"
Can't help if you don't show us what was asked for
do you guys know any good vids about state machines? I am tryin to find a good vid but every one i found the comments are saying "no thats wrong do this" or "its better this way".
i did
here
How is that the inspector of the object?
That is you saying something
Which is not what was asked for
it just Text and Button
Take a screenshot of it and send it
IheartDev has a good one
okay ill checkem out
https://youtu.be/qsIiFsddGV4?t=53
watch this one first though
https://youtu.be/Vt8aZDPzRjI
i just want to click that white button and change text on score
loll i was actually watching one of his vids @rich adder why does he have multiple state machine tutorials? im guessing the most recent one is the best?
I watched the second one twice
This is not the inspector of the text object still
its a more modular version using generics
The inspector is blank
it just defualt
okay, Ill follow it, alot of new concepts i understand but cant code yet
THERE WE GO! Lol
As nav said as the first response, that is TextMeshPro
takes doing it more than a couple of times to really
You need to do this
#💻┃code-beginner message
yea im excited to get it down, but i hate the low reward at first
just fix code?
I dont know what most of it means yet so i always say "oh i shouldnt need that" and end up stumping myself
Yep, add the one line, change the one word
That's it
Text is for the legacy text component
You are using TextMeshPro, which is different, and cannot be referenced as Text
After i finish movement, what kind of concept should i learn next?
ty
advance movement
:0 whaaaa
Make/release a complete game - it doesn't matter how mediocre it is. Then focus on improving/substituting individual parts like hud/ui and whatnot, knowing that the game is at least complete already. Follow a tutorial if necessary.
How can I get my enemy to go after the players position and if it touches the player then the player loses a life and the enemy dies
If I make a few scripts for a state machine, should i make another script to get the input from the new input system? or should I split up the inputactions into there respective state?
i find its nicer to have the input just handled by one class. makes it a lot easier when you want to change something about how input is handled, and you only need to change one class rather than every single state
I mostly need help with the enemy finding the player position and walking to him
Okay, ill try it out
unity's ai (navmesh) is the quickest way of setting this up. as for getting the players position, you simply need a reference to the player's transform. You can get that however you like, possibly with it being some public info, or maybe even gotten through a trigger enter.
Yo i kinda need some help again, I made the enemy move and stuff like that and now that i made a script to take out the players health i get this error
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "Player")
{
Destroy(gameObject);
playerLogic.GetHit(1);
}
}``` error is at playerLogic.GetHit(1);
so playerLogic is null
error says otherwise
using System.Collections.Generic;
using UnityEngine;
public class PlrLogic : MonoBehaviour
{
public float health = 3;
public void GetHit(float damage)
{
health -= damage;
if (health <= 0)
{
Application.Quit();
}
}
}
this is PlrLogic
where is assigned
in the enemy script
I love the if health 0 or less just quit the whole damn game
and how to i assign it
how did you assign playerObj
then do the same thing
it doesent let me drag it in
is one of them a prefab not in the scene?
whats a prefab
can you show inspector of what you're trying to drag in
screenshot it
Hi, I am facing a strange issue, I basically want to Move the road (lane) towards a position after getting instantiated. So In the following LaneIncrease(), isLaneMoving bool becomes true, and so does the instantiatedLane gameobject gets assigned a prefab. But in the Update(), it doesnt get updated. I always get isLaneMoving = false, and therefore my lanes are unable to move.
Image
Image
The function LaneIncrease() is called by picking up an item, which itself has a script called PickupManager(), it calls the method of LaneManager by referencing
It needs to be on a gameobject
you have to drag the gameobject with that script
Enemy has a player logic?
u told me to drag the gameobject
if its a player script why did you put it on enemy
idk
wait
im stupid lol sorry
i had to drag the player in the player logic
thanks
but the game doesent quit when 3 enemies touch me
Application.Quit does nothing in the editor
You either want to exit play mode or do something else
ok thanks
excuse me, why did my character stopped at that specific spot? it makes no sense.
The specific spot it looks like... in the edge of ... that thing.
hard to say without
knowing the movement script for starters
holy shit
unity does have vector4
its for colors
which makes sense
a color is RGBA
a vvecrtor 4 would have 4 inouts
https://docs.unity3d.com/ScriptReference/Vector4.html its just a vector 4
i know what it is
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
jesus
i see the problem
it aint got no gas in it
if I already created a full script with only 1 bug in it, should I keep the script and change it to add a state machine or should i redo it from scratch but use it as reference?
I am having issues with my coding. On Unity, its saying I made some mistakes but I am not able to identify the issue on Visual Studios
please delete this its hard to read on DC, and send links
we told you what you need to do
configure your IDE first
@lean basin i think you have the same friction issue i do, have you added a physical material to your rigid body?
Im trying to figure out how to configure it. I'm looking everywhere to find resources but so far, no luck
we linked you to it
!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
and do you get caught on it when your jumping?
Click it
I suggested you temporarily remove the script with errors before doing the config so everything compiles properly @acoustic sun
do you understand how to do that ?
There are no rigidbody, no Collider component so no PhysicsMaterial from my understanding. I'm using CharacterController.
As has been stated too, you may need to comment out your code so Unity can compile and connect with your IDE properly.
Then you can uncomment your code and fix your (now highlighted) errors
there is a lot going on here.. Start debugging
also I would do some ray checks make sure no lingering invisible colliders somewhere
I checked on there, pretty much I did everything on there
Is that a "pretty much", or a "I did"
I did
- Making sure the external tools setting is set in Unity.
- Making sure the Game development with Unity workload is installed.
- Make sure you have no compiler errors by commenting out your code and letting it compile.
- Try restarting VS by reopening it with Unity's menu: Assets/Open C# Project
For 4. Its letting me reopen it with the unity menu
Am I supposed to get Github as well for this?
hmm, there are no invisible collider.
I'm not sure what else to debug.
The character is on ground and is in running state and doesn't change at all, there is not really much going on, it doesn't even call SnapToBottom()
The specific spot where the character stopped and seem to be trying to shove it's body to the ground is when it's hitting half wall? like a wall in the front it that is not high enough.
I really doubt you can "get GitHub"😬
Or anyone for that matter. So, no.
Okay because I am getting GitHub Copilot norifications on my script
maybe you installed it 🤷♂️
You tried another scene ? is it only that spot or just any edge?
did you Debug.Log yourisGrounded
the built in CC one is kinda ass
would double check // Snapping logic also
also not sure what you mean by
I'm not sure what else to debug.
there isn't any debugging in here xD
It probably just has no where to move on that specific area. Im on mobile so it's hard to see exactly what your script is doing.
Usually a collide and slide implementation would be used to avoid cases like this.
any edge that is in similar shape.
Hmm I tried to debug isGrounded (i mean the CollisionFlag) it stays grounded except when going downhill in a big slope but the code is stuck when Im going uphill.
unfortunately the SnapToGround() didn't get called at all during the time it got stuck. so... the snapping logic is not called.
But I tested the snapping logic, it worked as expected, it doesn't switch grounded state at all when the slope is not that big.
The collide slide thing!! what is that?
In another game engine (godot) I would usually use move_and_slide() as opposed to move_and_collide() which will slide to avoid this problem. I'm not sure what is the equivalent thing to do in unity.
You would have to implement it by checking what object is in way, then project your movement
Honestly when trying it myself, it was still buggy or annoying in some odd cases. Your best bet is really just use an existing solution like KCC or just use rigidbody movement.
KCC? is it this thing https://github.com/nicholas-maltbie/OpenKCC ?
or are there other more simple one?
I believe I tried using the one you linked and it is really buggy in some cases. Player can get stuck after very quick testing
It definitely will take some learning to use, I dont even use it because I just wanted to setup something less bulky. I opted to just use rb movement
that looked more interesting than the link I posted. Thank you for your suggestion!
is it easier to manipulate my code with 1 bug in it to a state machine or should i start from scratch?
Depends on your code and personal preferences
im just makin a new one with a reference
whats a better word than 'look
public Vector2 MovementAction { get; private set; } is this a class or a variable?
That's a property
Hi guys.
I want to check in a OnTriggerEnter2D if the collision is in specific layers.
I found this post https://discussions.unity.com/t/using-layermask-in-ontriggerenter/216825
But this won't work.
LayerMask.NameToLayer isnt what i want because I already have the layers to check against in a _collisionMask variable.
The second answer also doesn't work:
void OnTriggerEnter2D(Collider2D other)
{
if ((_collisionMasks.value & (1 << other.gameObject.layer)) > 0)
{
_health.TakeDamage(10);
print("Hit");
}
}
Ok the second answer works now. I don't understand the code and it feels a bit hacky. Is this a good way? Basically I want to create an all purpose Hurtbox I can attach to enemy or player and only collide with things I want to specify. For example the player should not collider with its own bullets.
Hello, is there any way to let’s say use layer or layermask as a trigger to OnTriggerEnter or Exit? I’m making a fps game and I currently have it set to the Player tag but I realized that if one guy goes into the trigger it will show up for everyone. Is there any way to prevent this? For example as mentioned earlier use maybe a layermask?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators
these are the operators it is using if you want to see what it is actually doing
Also more info on bitmasks/layermask.
https://unity.huh.how/bitmasks
Errow :- Assets\MyMadeScripts\RaceScene.cs(11,30): error CS0122: 'TimeTrialManager.EndTimeTrial()' is inaccessible due to its protection level
code =
using UnityEngine;
public class RaceScene : MonoBehaviour
{
public TimeTrialManager timeTrialManager;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("FinishLine"))
{
timeTrialManager.EndTimeTrial();
}
}
}
The error is pretty clear, what part confuses you? Look at the method declaration for EndTimeTrial
i cant undertand anything of this error
can anyone help me, to understand a "Github Use Documentation" ?
it s only 2 Lines, but i do not understand what to do
( JAva )
Have you looked at the method declaration yet?
the "Protection" is not accessable. Maybe: for example , it s private, or protectet.
So : timeTrialManager.EndTimeTrial() can not be accessed
using UnityEngine;
using UnityEngine.UI;
public class TimeTrialManager : MonoBehaviour
{
public Text timerText;
public float timeLimit = 300; // Set the time limit in seconds
public float elapsedTime;
void Start()
{
UpdateTimerDisplay();
}
void Update()
{
if (elapsedTime < timeLimit)
{
elapsedTime += Time.deltaTime;
UpdateTimerDisplay();
}
else
{
EndTimeTrial();
}
}
void UpdateTimerDisplay()
{
timerText.text = "Time: " + FormatTime(elapsedTime);
}
string FormatTime(float timeInSeconds)
{
int minutes = Mathf.FloorToInt(timeInSeconds / 60);
int seconds = Mathf.FloorToInt(timeInSeconds % 60);
return string.Format("{0:00}:{1:00}", minutes, seconds);
}
void EndTimeTrial()
{
timerText.text = "Time Trial Finished!\nElapsed time: " + FormatTime(elapsedTime);
// Add any additional logic for time trial completion
}
}
This is a unity server, which uses c#
all are public
No they arent, it is private by default
i know, would be more nice if unity use a package manager, give you your packages you buy. But they dont.
So ... i ask for help.
Awesome, thx very much. That site is very helpful 😄
void UpdateTimerDisplay()
{
timerText.text = "Time: " + FormatTime(elapsedTime);
}
Change this to :
public void UpdateTimerDisplay()
{
timerText.text = "Time: " + FormatTime(elapsedTime);
}
ok
try again, should work.
remember
Everything what is NOT Public, can be NOT acessed from outside!
ik
hey bro the error is still there
Assets\MyMadeScripts\RaceScene.cs(11,30): error CS0122: 'TimeTrialManager.EndTimeTrial()' is inaccessible due to its protection level
using UnityEngine;
public class RaceScene : MonoBehaviour
{
public TimeTrialManager timeTrialManager;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("FinishLine"))
{
timeTrialManager.EndTimeTrial();
}
}
}
Please share the code containing EndTimeTrial()
Just curious, is your ide configured? Also save your other script
i use sublime text
vs code
Please use a proper !ide for using Unity, we can't/won't help users without a misconfigured 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
my foult. Was because i am in other things with my mind.
public void EndTimeTrial()
{
timerText.text = "Time Trial Finished!\nElapsed time: " + FormatTime(elapsedTime);
// Add any additional logic for time trial completion
}
Please read above, don't help users that have a misconfigured IDE
now i saves both the scripts
stop spoon feeding too. The guy didnt even understand how to fix the error after your first "fix"
And there you have it, the suggestion was completely ignored since the initial issue is now resolved
can i ask what a "Misconfigured IDE" is ?
Lack of syntax highlighting, no proper error handling by the IDE, no quick fixes by the IDE
thanks to @barren aurora and @eternal needle
Go get a proper IDE and get it configured. You really shouldnt have been spoonfed the answer. Also I'm surprised you dont have one configured since I've definitely seen you ask questions here before.
Maybe.
BUT
i start same way.
You learn by doing.
Did you ever think about, that the Situation to put "Content" in TONS AND CONTAINERS into the Mind of a Guy who only want to know, how to fix an error
is contra Productive ?
if he want to stay, and countinue, and to better up his skill, he will learn.
but you do not help him, for a singel short Question, if you "Pusch 1000Ths Sides of Code" inside his mind, for such a small question.
this bring ppl to go away, not to learn things
here is best Example.
i startet, with the Question "how to collect a trigger"
and be BOMBED with 10 000 C# Books ( i never read )
Today, i am in since 8 Years, i am C# Pro, and have much complicatet Unity Projects.
BUT I WOULD NEVER START TO READ 10 000 Side Documentations
For a short Question!
That's a lot of words
The problem is that rather than explaining the problem you just give the updated code as-is, without explaining what went wrong
That's not learning
Honestly I dont even understand what you're trying to say with half of that. It is a requirement to have a configured IDE. I also have taught students, you spoon feeding answers is NOT how people learn.
If someone goes away by the idea of having to learn, they are not cut out for coding. That is the reality of it
see above:
i told him:
Everything what is not public, cant be accessed.
but no problem
I be on my way to go here.
Because:
Help can nobody.
So : your game, you rules, not my building place.
I have a hard time reading this, sorry
None of that makes sense yea
!warn 892828741443674192 As you have been told previously, you need to have a configured IDE to get help here. Sublime text is not a valid IDE. You can use VS Code, Visual Studio, or JetBrains Rider.
electro_op has been warned.
You told him an incorrect answer. He used it. Error didnt fix. He came back, clearly not knowing what to do. You gave another answer directly.
Now he will come back tomorrow with another issue, without getting a proper system setup.
It was clear he thought methods were public by default, but now he wont learn otherwise.
Luckily for everyone, if that happens they will be muted
Short and Deepl:
a beginner, who probably has only one code error in an asset, will hardly read 10 C# books and start looking at millions of Toturials.
You're more likely to scare them away.
But: that's not my problem, I asked here briefly, no one likes can want to help, I'm already gone again.
Have a nice day.
Nobody is asking them to read 10 books and look at millions of tutorials
they're being asked to configure their IDE and learn the basics
Ok
no colliders?
Yes, the first mistake was mine. I set the wrong method public.
My goodness, this is the beginner channel.
YES ! as a pro you always say. learn it right.
But you want to have fun with Unity first, not study 10,000 documentations.
He probably imported an asset and it has an access error. If he keeps at it, he will learn. But overwhelming him with books and confusing documentation is the opposite of fun.
Get something right first.
Then see where the problem lies.
How many get in and are out again after 2 weeks?
Does everything always have to be so doctrinaire? that's ... very fun-killing.
Especially with such a simple request, it's not a complex script. You helped him faster than you explained the documentation to him. hm ?
Stay human, always a good choice
💪
Yes, I understand you too.
We've all been through it at some point.
You know, I started with Udemy.
in the first "WEEK!" Toturial, I didn't know how to take 10 arrows from another collider. It wasn't explained there.
Then, when I asked in a forum, they all hit me with half 10 year courses. That is: absolutely counterproductive! Today I have extremely complex projects, so comprehensive that you wouldn't even want them to be true.
I learned everything myself.
But nobody has been able to help me with a book. You have to gain experience first. This : is the start.
You can turn a blind eye to that, can't you?
NOTE: nobody new even knows what an IDE is.
Even I don't know that.
just as a remark, and my things work wonderfully...
!codeblocks
📃 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.
Also, the whole issue was related to a basic c# feature and not Unity. Stuff like these should be know if you start with Unity. Beginner Unity is not beginner c#
Stuff like this can be learned from tuts that can be found in the pinned messages
is using localEulerAngles better than localRotation = Quaternion.Euler?
they are identical
no Collider in the character object. CharacterController provide it's own capsule collider which we can't edit like normal Collider
If your issue was the physics material I wouldve pointed it out before. The person who mentioned it is also a beginner. The physics material would be an issue if you were moving with rigidbody movement. The character controller basically teleports your player, while solving for depenetration meaning it wont get stuck in objects.
NOTE: nobody new even knows what an IDE is.
Even I don't know that.
just as a remark, and my things work wonderfully...
Luckily the message that is sent when configuring it is requested lists them. Google tells you what they are, and so does asking.
If your IDE is also not configured then that's a fundamental and massive issue you should address before proceeding
Yes, but only.
It's a newcomer! Don't make such a big elephant out of it.
I don't use "IDE" for me it's Unity Editor, and Visual Studio. That's it. I don't like abbreviations.
and overall, he could save his script, and he was helped. So he seems to have a working IDE.
But good now. I helped him, why don't you stone me for it? A community where someone helps someone new. How can he.
Let's hit him with rules, requirements and compulsory events that he'll never understand as a new member, so that we can have fun and he's not helped.
And now: stone those who help a newcomer.
Hail community, the master has spoken.
In all seriousness and without irony: I'm off again, I've got other things to do.
what you said
just doesnt make sense
i don't use IDE - i use Visual Studio 🤔
hi, can this one be converted to a Ternary operator?
yea
act1SkillImgs[0].color = skillUnlocked1 ? Color.white : lockedColor;
It's against our rules to give answers to people who do not have an IDE configured. Being able to save is not enough, you need autocomplete and error highlighting. If you want to continue complaining about these basic requirements you can write a blog, because they are not changing
Thank you so muchhh!!
Short: i use VStudio, this IS an ide, BUT i dont call it this.
nobody knows this "Short words"
here in germany we tell this DBDBHKP
also nobody know.
I do not use visual studio
Others don't either, hence we use the word that refers to the group
every programmer that knows the basics, knows what an IDE is (well even not programmers)
@rare basin @north kiln
Shortly:
The question was awnsered.
and i have other things to do, than to talk about IDE or not IDE,
or to waste my time, with "rules" for nothing.
it was just 1 word to change
the problem of the guy is solved.
That s it.
it is that easy, truly. it is.
Then stop talking about it rather than constantly saying you are "out" but yet you aren't
Go away then, please
just i was away, you did start again.
Just; it s completly not senceful, to discuss how about to call an IDE,
it s not simple.
it just wastes time.
and also all what i did say:
it was 1 word to change
no need, to avoid to help others, just because they should read tons of sides.
This is not nice for a noob.
stay familiar
and be nice guys.
This is just a noob, want to play around with Unity.
maybe, he can stand by us, or you make him crazy with 10 000 rules
and he stop.
think about.
What's the best way for me to use a random sound clip when something is triggered? I don't want my enemies punches to all sound the same. This is what I've got at the moment, but it's only player the first clip, never the 2nd
Random.Range for int is exclusive
(1,2) can only generate 1
(0,4) can generate 0,1,2,3
!warn 176068058241171456 it's a requirement that newcomers configure their IDE, and we do not want people to answer their questions to avoid time wasting. Your argumentative attitude is unwelcome and unhelpful. If you don't want to follow our rules you are welcome to leave.
smokingheadstudio has been warned.
so I should change it to 1, 2 , 3?
If Statement:cs if (condition) result = first; else result = second;Ternary:cs result = condition ? first : second;Note that ternary requires the first and second results whereas an if statement doesn't necessarily require any results (nothing has to be done in an if statement).
I'm not entirely sure what exclusive means. It means it doesn't include the last digit?
Does you know why it's exclusive?
So you can simply pass an array length without requiring subtraction
to align with typical behaviour with arrays i guess
Thanks!! ❤️
Okay, thanks
{
``` trying to move the raycast up off the ground to detect the playe but it wont move seems to shout ground level only
seems to cast at ground level rather then a waist height
I have one more serious question before I leave again, because: I could always help myself without this channel 🙂 And I'm quite happy about it when I see this but:
How do you know if it has a configured IDE ?
that's the crucial question.
Because a C# code says nothing about it.
experienced dev can just tell that by looking at code screenshots
code not auto completing, different types coloring, no errors highlight
Red error is red error. Do not tell you what Editor is saved for unity.
Lack of highlighting, saying Miscellaneous Files in the top left of VS, a mass of stupid errors, posting screenshots of compiler errors in the Console window, an inability to connect the debugger.
Also poorly formatted and aligned code
Yes, well. Don't make an epic program out of it.
I've got other things to do than argue.
I helped one, that's it. His problem is solved, done.
Your playground, your rules.
And as far as I'm concerned:
I'm off again.
Play a little more. Fortunately, I know how to help myself. For almost 9 years now.
But where I don't ask - I now know 🙂
hehe. well then 🙂 Have fun.
Delusional 😄
Keep programming without your IDE configured
have fun
When are you "finally" off?
An unconfigured ide would usually yield minor mistakes like missing semicolons, incorrect/invalid syntax from lack of auto complete (no awareness of available members), typos, improper text indentation on some text editors/ide and a whole lot more. It's like identifying if someone wrote their own code or use illogical ai code.
yeah. 20 Databases,
more than 2000 GameObjects scriptet
60 FPS
errorfree.
i go play again 🙂
see you
Wait, you are programming for almost 9 YEARS NOW
without your IDE configured?
the fuck did I just read
somebody mute this troll lol
Not trying to say anything but anyone who brags probably hasn't been coding long enough yet.
he's coding for 9 years
2000 game object scripts, no ide configured and 60fps
Note:
Things must - work -
I don't care what you mean by a "configured IDE". Ergo: I don't read through what garbage is written there if everything works perfectly.
If I encounter a problem, I solve it.
It's like patterns: yes, they can make sense.
But code is code, the result has to work.
As long as your car runs, there's no reason to rewrite everything just because you don't like the way you capitalize variables.
... just think about it.
The result speaks for the work.
Not the form.
I mean, if you've code from the 80's, 90's or even 2000's you'd know tech comes and go... everyone's always learning.. "pro", what's that?
you are missing entire concept of having your IDE configured, at this point i think you are just a trolling kid tbh
so im done talking
don't spam the channel with offtopic now
can someone help me? my movement jump fall run and idle is okay but when i added a movement climb suddenly my character is moving so slow and not jumping
💪
You not even have an idea how complex my projects are.
And they are.
but this is not the point.
Just: to help each other is the point, and not to discuss long terms
against a noob.
Can you send a screenshot of your IDE to this channel lol
i'd love to see some code sample
from your complex project
could you send it?
i see your "IDE Bot thigns" just: i have extern Editor configured, what s the Problem = I always install @ hand, never with Unity package.
can someone help me? my movement jump, fall, run, and idle is okay but when i added a movement climb suddenly my character is moving so slow and not jumping
don't spam
will be senceful to tell a little more. ( and have an configured IDE 🤣 )
shortly:
you need to send some Code, or Screens or something the Problem shows.
this is not helpful what you ask here, because: can have a lot of reasons.
Send some relevant !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.
@barren aurora is there any chance you could send a sample code from one of your complex projects?
for what ?
you not even know my project.
so makes no sence