#๐ปโcode-beginner
1 messages ยท Page 161 of 1
thanks mate ๐ lets hope the refactor isnt bad.. b/c it needs it
sry if i dont understand something
Which of these lines sets scr to something other than null?
its false
where do you tell the code what scr is
ill send the code
how
scr is absolutely not false
bool not set = null
except for stuff like structs
not even talking about setting it automatically in the first frame
cuz its not in any item's range
I don't know why you're showing this code this has nothing to do with the previous question
so the bullet goes with the green axis, which is Y if i remember correctly ?.
this mean your movement logic is good, but the issue is the rotation your are giving to the projectile when spawning it
yes, green is Y
InItemRange has absolutely nothing to do with src
They're not the same type and they're not even in the same class
maube use a look at, but this depends if you have a gameobject always tracking the cursor position
we aren't talking about any bools
Again, I do not understand why you're showing us this completely unrelated code.
in the script with the error
how do you set src
what value does that variable hold
You have a very weird misunderstanding of how references work
probably
scr is a field of type PlayerInRange
It is not a bool. Nor is it a float or LayerMask or Transform or any other type that happens to be stored in a field on PlayerInRange
It is a PlayerInRange
okay
The reason that scr == true worked is because of how Unity lets you convert any unity object into a boolean implicitly
e.g.
if (scr) {
Debug.Log("scr is a valid unity object");
}
This has nothing to do with InItemRange
It is completely unrelated.
scr.InItemRange would be the value of InItemRange stored in the object referred to by scr
i can reference a bool form the other script
Sure. Assign a reference in the inspector, then use scr.InItemRange to read the boolean field
this would error yes ?
sometimes when i just do if value it errors, but if value != / == null it doesnt, is there a reason ?
No.
so private bool src;
You can. You have to reference that script. You need to tell the code which PlayerInRange you want to get the value from
The reason that happened was because value was not a UnityEngine.Object derivative
UnityEngine.Object is where the implicit conversion to bool is implemented
You can't just throw any type into an if statement and have it convert to a bool
ah okay
so List<int> would not work
could you write me a script quickly?
No
No. You already have the script.
thats why for ie you cant do if GOref
You need to make incredibly tiny changes
i just want the reference
You also need to pay attention
because I've already indicated exactly what you need to do
because unity isnt "converting" GOref to a "bool" ?
its easier for me to learn by looking what changed and understanding how things work
you can absolutely do if (foo) where foo is a GameObject
๐ซ
sum1 pls help been stuck on this for hours now
then why do i remember does error i had
it's going to be incredibly hard for you to learn anything if you refuse to even attempt to solve your problems.
cuz im having problems with understanding complex stuff in a language i dont know well
unity allows null checks by just saying if(the object)
Read this. #๐ปโcode-beginner message
thats my case
Specifically look at the "Serialized references" section
you probably had some other type
also, in chsarp can you create a method so it gets used when trying to print or evaluate a class instance ? can you even do this with structs ?
like in python, __str__
the thing is i dont want to do it through the serialize field
ToString()
cuz i will be creating a lot of items with this script
and i dont want to assign everything manually
If every object will refer to the same ItemInRange component, then consider the "Singletons" section
sigh
https://paste.mod.gg/itvbnzmmiqed/2
my code ^^
anyone know why when i start the game, and the player falls, i cant move til i jump, same as when i double jump, when i land i move very little then i cant move
A tool for sharing your source code with the world!
there's enough spam in the world already. i'd rather not get buried under more of it
I have a hard time believing this, though.
if a parent is disabled and enabled, will the childs "onenable" get called?
OnEnable runs exactly once.
If you can't help someone, you don't need to be their ChatGPT mediator. @cursive viper
also, I presume you mean deactivated and activated
just FYI, when using that site to share code make sure you include the .cs in the file name so it provides the proper syntax highlighting
you can use OnEnable if you want to run every time you become enabled
wow, the documentation for OnEnable is bad
This function is called when the object is loaded.
true, but....
but thats the thing i cant learn shit or at least not learn that much with reading shit i dont understand
then follow some tutorials to get guided help
i have to see it work and see how every single line works
people aren't going to walk you through literally every step
but there isnt a tutorial how to link a bool from another script
Of course there is.
cuz it probably requires one line of code
class someClass {
public string ToString(){ return "this is me"; }
}
someClass instance = new()
Debug.Log(instance) //prints out "this is me"
instance.length //prints out the length of string "this is me"
string test = "yoo";
if (test = instance) //this would not error
so this examples would work ?
i dont want them to do i just want to learn how to link a bool
really best docs for most unity messages is the ExecutionOrder page from the manual
No, ToString isn't an implicit conversion operator.
You can implement one if you want.
been tyoping for like 15 minutes to just link a bool from another script lol
* i wrote length but i dont remember the exact keyword
public static implicit operator string(MyType self) {
return "hello";
}
I want to say that's correct.
This enables a type to implicitly convert to another type when needed.
it would work for what ? by default
consider reading the website you were linked to
it explains quite a lot
thanks, might be usefull
can this be used for a struct ? since struct can have methods
public struct Foo {
public static implicit operator string(Foo self) {
return "123";
}
public void What()
{
if (new Foo() == "123")
{
Debug.Log("OK");
}
}
}
this compiles.
oh ye i forgot about that, thanks
ToString is simply a method that's defined on every object
like, every C# object, not just every Unity Object
hey would any body tell me what is the best thing to download if your trying to learn c sharp visual studio code or visual studio
It's used by some things, like the + operator when concatenating an object to a string
visual studio
But that's different from the language being told "hey, type Foo can implicitly convert to a string"
visual studio code is just a text editor with some fancy features pretty much
I believe the common wisdom is to favor Visual Studio
Get visual studio through Unity Hub so it configures it for you.
I use VSCode for a lot of things, so I picked it
(VS is also not really available my macbook)
I have a movement script and I want it to have no velocity cap when falling down. The way to do this as far as I know is to set the rigidbody's drag to 0 however I also want the movement to feel responsive, what do I do?
what doesn't feel responsive with 0 drag?
is the problem that you ice-skate around?
or are you talking about movement specifically when falling?
yep
One option would be to apply your own drag.
Vector3 fallingVelocity = Vector3.Project(rb.velocity, Vector3.down);
Vector3 movingVelocity = Vector3.ProjectOnPlane(rb.velocity, Vector3.down);
movingVelocity = Vector3.MoveTowards(movingVelocity, Vector3.zero, Time.deltaTime);
rb.velocity + fallingVelocity + movingVelocity;
generally when airborne
This would slow you down by 1 meter per second per second, but only horizontally
Proper drag should be proportional to your current speed.
Unfortunately the obvious answer doesn't quite work right...
Vector3 fallingVelocity = Vector3.Project(rb.velocity, Vector3.down);
Vector3 movingVelocity = Vector3.ProjectOnPlane(rb.velocity, Vector3.down);
movingVelocity = Vector3.MoveTowards(movingVelocity, Vector3.zero, movingVelocity.magnitude * Time.deltaTime);
rb.velocity + fallingVelocity + movingVelocity;
https://unity.huh.how/lerp/wrong-lerp
It's the same sort of problem as this
Although, if it's happening in FixedUpdate, then it's probably fine.
(this code slows you down twice as fast if you're moving twice as fast, which is roughly how drag should work)
if (ballGrabbed && !grabPressed)
{
ball.GetComponent<Collider>().enabled = false;
ballRb.velocity = velocity;
ballRb.MoveRotation(Quaternion.RotateTowards(ball.rotation, ballHolder.rotation, rotationSpeed * Time.fixedDeltaTime));
return;
}
if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
Debug.DrawRay(cam.position, fwd, Color.green, 10);
ballGrabbed = true;
grabPressed = false;
}
Anyone know what I could do here? If I re enable collision in between the if methods, the ball will immediately be "grabbed" again due to the second if method running right after, but if I don't re enable collision the ball will no clip through the floor
thanks
Since we're speaking on Directions and stuff (earlier) I have a question..
- I wrote out this script (trying to make it generic enough to use thru-out my project
- Everything works pretty much the way I think it should only the
additionalOffsetpart of it
- Everything works pretty much the way I think it should only the
The additional offset was originally b/c the UI i was using on it was backwards and used a 180 offset so it would be facing directly..
That's when I noticed how the Transform gizmo would look upwards first and then back down.. I'm pretty sure this is the way I'm adding the offset
(causing quaternion magic stuff)
heres the script : https://gist.github.com/SpawnCampGames/47b2edb673714b5c6fa1e7c30b371e6c
and how I add that offset // Apply additional offset directly to the desiredLookTarget desiredLookTarget += additionalOffset;
anyone know of a better way to add the offset?
i tried trasnform.forward and my bullet is now going only in the direction , why the y and x is static,
can i replace string with other type, so i can use this for other use cases ?
okay ty
like
// inside a class
public static implicit operator int(MyType self) {
return 3;
}
myClass inst = new()
if (inst > 3) // this would not error
wait, this may be correct, it may just appear wrong to me.. i'm going to test w/ some raycast and drawlines right quick
there is nothing special about retrieving any field from another object -- all you have to do is get a reference to the object in the first place
the most straightforward way to do this is a serialized field: you drag an object into a field in the inspector and you're good
If you don't want to have to manually assign it, then you must find another way to get that reference. if everyone uses the same reference, then the singleton pattern is appropriate (as described in that link)
otherwise, you'll need some other mechanism to provide the reference
Important note: There is no alternative to learning how to reference objects. That is programming. Almost every problem is some form of "How do I get a reference from here to there"
There is no shortcut
ya, so i think this is okay. i think it appears to be looking upwards b/c it is.. when the camera goes across it, it has to look upwards b/c its so close to it
trying to set an objects sprite to this other one and it wont recognize it unsure as to what im doing wrong
show where you declare BerryBushEmpty
i need to declare it?
u have to tell the IDE what it is...
Well, how else will your code know what to use?
and which one it is
yeah true, i think i got it now
yeah i get it now
jsut didnt think i had to declare it for sprites for some reason dont know why i thought that tbh
- Hey Unity, I need to use a sprite;
- I see that, what sprite are you going to use
- This one
- Thank's, I'll remember you're going to use a Sprite named
whateverYouNamedIt, and you want that sprite to use this image/sprite
- Thank's, I'll remember you're going to use a Sprite named
thanks for the help btw
ya, if u can figure out how to get unity to know what i intend to use, b4 i tell it you let me know
that'd be extra beneficial ๐
actually i think there might be a way to do that if im understanding this post im reading correctly
i currently dont really need this but if youd like here it is https://forum.unity.com/threads/create-spritelibraryasset-by-scripts.1168610/
ya, I don't do runtime creation stuff like that yet
ah i see
but good resource
Hi, I'm using Nomnom's Raycast Visualization package in my project but it doesn't seem to work, doe smone knows why pls ?
Do you have gizmos enabled
Ngl what's that ๐ ๐
After verification, gizmos were enabled and I they show up when I call them through code
Then I can only presume you're not calling nomnom's via code, or you're casting in a completely different place
I just finally fixed it, thanks for the help
how do i set the object reference to an instance of an object
first find out which line is throwing that error
first one i think
"first one" ?
this means that your script looked for an object with the component (script) PlayerMovement in the scene, but there were none
"i think" you should verify that by looking at the stack trace. although i can guarantee that it is the first one since that is the only line shown that can throw that exception
if you mean FindObjectOfType then you have no GameObject with PlayerMovement script on it
first line in update
also why aren't you just putting a field in the inspector and assign reference that way
well it says the error coems from update
i do have one
navarone is right, you should almost never use a FindObjectOfType inside an Update method as this is a very expensive operation, you should most likely set this in Start or elswhere
this count as a GameObject with the script, right
if the object or the script are disabled, FindObjectOfType won't find it
name man u got errors the script isn't even loaded
i didnt really know how to set it up
theres an error, you probable changed the name of the script or the name and the class don't match
ye i changed the name of the script to have a capita lletter eveyrwhere i could but ig it didnt update
Please fix any compile errors and assign a valid script
the code is same as before i just changed the name of the class and the script, and they do match
but its still compile error
before that the code could run without issues
Try removing the component and adding it again
wait i foudn the problem
somehow in one of the scripts a letter was removed fro mthe name and the script was saved ๐คฆ
lols
okay so this is how the code is now, i have put the player in the serialized field, but the update isnt really update the fireballs rotation based on the plays position... any1 know why?
Try logging a, b, c, and rotation to see if they're what you expect every frame
I have 2 object classes, Suns and Planets. I want a list of all current gameobjects in the scene. How would I make a list store every instance of 2 different classes?
Or would I use a structure other than a list
Give them a shared parent class
Is that easy once you've already done a bunch of stuff with the original classes
If you need a list that contains both of them, chances are they have some sort of shared functionality you can move into the parent class
ehh suns are immobile and planets move around the suns. I want to use the list to store all current planets/suns so I can go through each element in the list when saving the current scenario as a preset that can be loaded later
So then presumably any functionality related to saving the objects can be put in the parent object
if i named the new class test would I just change the original scripts by making
the sun class into Sun : test
and planet into planet : test ?
Yes but don't call it test give it a name that actually explains what they actually are
yeye
ty
Oh does everything In the planet and sun script go into 1 big mega script for the new class
Anything shared between the two goes into the new class
Not sure how visible this is, but when running my game there seems to be some sort of white border that flickers, not sure if this is a visual glitch or I may have done something to enable this
I don''t actually think I have a video capturing application currently ๐
I think it's the camera? Could be UI related, but turn off gizmos in the top right to ignore it completely
hmm good call, but it seems to still persist
you didn't turn off gizmos
not this?
yeah it's the camera's frustum
look in the top right of the game view window where it literally says Gizmos
you've toggled gizmos off for the scene view
oh wow... Well I did think that this was most likely just me not knowing where some very common button is supposed to be located, TYSM both of you <3
https://getsharex.com/ this is a solid screen recorder, in case you need one later..
file sizes are pretty small
ahh tysm was about to get obs lol ^^ but might get that instead :)
OBS is good for recording high quality, but ShareX allows u to just record sections of the screen (or windows that u select) and the file sizes are small enough to share pretty quickly
If I modify the ScriptableObject values (int, float) via code in runtime, do they save between sessions?
not in build
if you modify an asset then those changes persist in the editor. but not in a build
so if i restart the editor
This is a good argument in favor of just never mutating ScriptableObjects. It can lead to difficult bugs that behave differently in development environments that don't happen in builds
the changes will be present i made in runtime?
If the change occurs in the editor, it will modify the SO asset itself permanently.
If the change occurs in a build, there is no asset and it will reset when you restart the program
For serialized fields the changes will persist across sessions in the editor but not in builds
And if i change the SO via code in runtime, in editor?
okay
If the change occurs in the editor, it will modify the SO asset itself permanently.
got it thanks
oh yea, it gives a value between 0 and 1, or probably -1 to 1. cuz its arccosine. what do i do wit hthat value to make the fireball actually look at the player? i actually cant rly figure this one out, i tried multiplying with 360, but its not really it
2D or 3D?
2d game
one more thing I dont understand. When making changes via runtime (in the editor) to the scriptable object, it is permamently - i get it. But I don't have any changes to commit in git. When I set the ScriptableObject as SetDirty() then i do have changes to commit in git, why is that?
Changes in git means the file on disk changed
Which is different from the object in memory
When you set it as dirty the editor saves the in-memory changes to the file
Which direction is "forward" for your fireball?
Is the sprite facing up, to the right, etc.
right
Hey folks, I've been having a strange issue while writing a script that's used to figure out whether a gameObject is colliding with something from a certain direction. The error occurs whenever the subject gameObject initially comes in contant with the ground, setting IsGrounded to be true (which works fine), however the IsOnWall and IsOnCeiling properties are set to true as well for some reason, before quickly being set back to false. This creates a handful of bugs related to the gameObject's movement and collision handling. I've been struggling with this one for a while, so any help is appreciated.
Here's the script I've got:
// Had to cut off some parts of the script that (I hope) weren't related
public class TouchingDirections : MonoBehaviour
{
public ContactFilter2D castFilter;
public float groundDistance = 0.05f;
public float wallDistance = 0.2f;
public float ceilingDistance = 0.05f;
BoxCollider2D touchingCol;
Animator animator;
RaycastHit2D[] groundHits = new RaycastHit2D[5];
RaycastHit2D[] wallHits = new RaycastHit2D[5];
RaycastHit2D[] ceilingHits = new RaycastHit2D[5];
[SerializeField]
private bool IsGrounded;
[SerializeField]
private bool IsOnWall;
public Vector2 wallCheckDirection => gameObject.transform.localScale.x > 0 ? Vector2.right : Vector2.left;
[SerializeField]
private bool IsOnCeiling;
void FixedUpdate()
{
IsGrounded = touchingCol.Cast(Vector2.down, castFilter, groundHits, groundDistance) > 0;
IsOnWall = touchingCol.Cast(wallCheckDirection, castFilter, wallHits, wallDistance) > 0;
IsOnCeiling = touchingCol.Cast(Vector2.up, castFilter, ceilingHits, ceilingDistance) > 0;
}
}
You can set the object's transform.right to the direction from the object to the player
You can get a direction between two objects by subtracting their positions and normalizing
so i didnt have to do all this?
Nope
Just set transform.right to the direction vector
Two simple steps:
- Get the direction from the fireball to the player
- Set
transform.rightto that
right is on your right
You can get the direction between two objects by subtracting their positions, and normalizing
how do i get the direction between the two
is this how u meant by get the direction
You can get the direction between two objects by subtracting their positions, and normalizing
ok so i looked into what normalizing meant and this is what i get:
Normalizing a vector means scaling it to have a length of 1 while preserving its direction.
What i have done so far is subtracting their positions and making a vector by it, and since i have to normalize it has ot mean we want it to be a vector.
what i see as the next step is to normalize, but i dont have a clue what it would mean in this situaiotn or how to do it, what is meant by "length of 1"
Hi guys, I am trying to learn NavMesh and how to figure an AI that chases the player (in this picture, the green cylinder). The player is supposed to collect the gold orbs, however, if the green monster collides with the gold orbs, they are dstroyed, depriving the player of the point. However, the NavMesh agent seems to have trouble following the player when the player is surrounded by the orbs, is there a way to have the NavMesh agent ignore the gold orbs so it doesn't affect it's navigation?
few topics there
if you're just getting a direction to assign to transform.right like digi suggested, then you don't even need to normalize it. also why do you have all of these single letter variables? just do transform.right = playerMovement.playerPosition - transform.position;
that's literally it. you are way overcomplicating it
@small dagger do the coins have mass? why do they stop the navmesh
or do they carve out the navmesh?
yes, the coins have mass. They are spawned dynamically throughout the game (when you collect one, another one spawns in at a random location) so I figured the navmesh was jsut reading them as an obstacle, and therefore can't find a path around them when surrounded by them
Oh actually, setting the mass to 0 seems to have fixed this issue... thanks for the insight!
If you spawn them dynamically, and they dont have any navmesh components, then the navmesh agents should just ignore it by default. Since they wouldnt be included in the baked area
dam ๐ญ
ok tysm
what separates a wall from ground here? Do you have independent layer masks or as you banking on that the collider isn't hitting below and right of you?
could consider using different layers for each of these types, otherwise may need to look into a smaller cast range if you really need specific flags to always be set
usually better to just not work with exclusive logic
I have a unity desktop application that connects to several microcontrollers. I am wanting to create a UI to interact with these devices, but accessible from another device. Say from the web browser of a phone or laptop. Main priority is for it to be accessible by devices on the local network, but connectivity over the Internet would be nice too. And while I'd prefer for the UI to be web-based, I wouldn't be opposed to having a separate Unity application on the connecting device.
What is the best way to accomplish this? It would be nice to build out the UI within Unity and avoid dealing with HTML or something.
hm ok, upon further testing you are right, I think my navmesh implementation was just really rudimentary and jittery, I will have to look further into implementing it correctly
Is this gonna be a unity to unity connection? You should look into how you're gonna connect with the microcontrollers first. If everything is within unity, then you have options like NGO, mirror, photon.
Try seeing what the path is as you play, maybe you just need to try baking the area again. Or maybe you have something else interfering with the movement
a random range is different every time it is called right? so if i put a random range in update its gonna be different every frame?
yep
every frame, update is called, and it will run the random function that produces a new number every time it's ran
Microcontrollers are connected, that's done. I currently have a UI, but it's just for that one application on the desktop.
The externally connected devices (not microcontrollers, the devices with the UI) don't strictly need to be within Unity if that's not the most sensible path.
so this is gonna play the death1 sound 33% of the time randomly?
I'm unsure what your question is really about then, are you just asking if you should use unity?
Either way would be possible. UI in unity might be harder to fully customize compared to building your own html/css but it's definitely quick to setup a basic few buttons
random.value <= .33f
Guys do you know why the Button Click sound is not playing when i click the button? I have 3 buttons: Play, Options, and Controls, where i set an On Click action to play the sound (that i attached to an empty object, then drag and dropped it into the slot under the Main Camera for which i wrote the code (e.g, public void playSound1() { soundPlayer1.Play(); } ). All of the 3 buttons were set up that way, but now only the Play button plays the sound and the other 2 dont?
Hi, I need help. I need to store possibly hundreds of data items, but they all need to be different datatypes, how can I store these? I want to use an array/list. I just need a way to store large amounts of data that are all different datatypes without too much strugle. Thank you!
ther are no errors in my code, and the sound actually plays if i set it on "play on awake", just doesnt play when i click the button
What's the context? What are these items and what are they used for?
What's the use case? You can store anything in just type object but you wont get to be able to do much with them unless the thing using it knows what to cast it to
and the inspector?
Alright, so it is for different events in the game, just to store the data so I can call it back to put the choices on the screen
Sound like it all should be text..?
It uses a repeating patern (string, int, string, int.) or something like that
No, not quite. I also use numbers to take it to another event if you choose a certain choice.
each event has an id
You could use a list of a serializable class/struct with a string and int fields.
Someone could help me? When i try to get to interact with something (basically like a button) it dont works
https://hatebin.com/usvvrbspwb
Then it sounds like what I suggested above is what you want.
Ok, I will check it out. I just started Unity about a week ago, but I think I can handle it.
here is the inspector of the button, sound attached to an empty object, and main camera (under which the code that plays the button click sounds is):
ty bty
is there anything to actually run the audio function?
In your code it just looks like a bunch of functions with nothing to run them
i saw it before dont worry about resending it
Could someone help?
Share a screenshot of the "button" inspector.
wdym with button?
ah but wouldnt those functions just play the sounds that were attached int he inspector?
With the first script...
this is what you mean?
hmmm should i put them all in the void update(); function? if so wouldnt that just play all sounds continuously with every frame
you need to run it in the function that detects when the button is clicked.
Take a screenshot of it at runtime when the issue happens.
ohhh wait lemme try
If you mean when i click it it only does E has been pressed
click it is pressing E, i said it wrong
A screenshot of the inspector just like before...
But at the timing after pressing E.
exactly like before
Is it active in the hierarchy?
yeah
Okay, then debug what object you're hitting.
https://hastebin.com/share/odobocebas.csharp
not really necessary to read this script to get what im trying to do but just put it here for context, but how would I switch to grabbing an objects rotation from a raycast hit instead of from a reference??
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
like this?
Also, I don't see "yes" printed, so it doesn't even enter there.
No... In your other script. We already established it doesn't enter into Interact. You want to figure out how far it goes and what condition is not getting passed.
But then where i place the Debug.Log
{
Debug.Log($"hit object {hitInfo.gameObject}");
hitInfo does not contain a definition for gameObject
collider.gameObject then. I don't remember the exact API. I'm typing from phone lol. Use the ide suggestions to make it work.
i dont have the 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
Then get an ide and configure it before proceeding with your issue.
Is that VS code? Follow the guide above to config it.
alr did
Now print the name of the hit object.
wdym
Also, this part of the script stills dont work
The code that I shared...
It should print yes but it doesn't
and i also did what you said and stills doesn't
Then it doesn't hit anything.
How do i fix that?
Wait... I think i know the problem
Possible causes, wrong ray direction, distance, lack of active colliders.
the script should be on the player right?
You tell me..? Does it need to be on the player?
Like to make the raycast
You're the one that knows the intention behind the code.
ATM your ray uses the interact source transform for ray origin and direction.
So it doesn't really matter where the script is. What matters is what transform is assigned to that field.
k am dumb
i had to make the source be the player
that's why i hate 2 min tutorials
Tutorials shouldn't replace your head.
You need to fully understand what you are doing even if you are following a tutorial.
so um....does anyone even know what this means?
hello im working on a player movement script i countered a few issues on the way,
my player jump is really inconsistent
i have been stuck for a few days and taught well why not just ask
Start from making all your add force methods being called from fixed update.
alright wil do
Share some more context on the issue maybe. When does it happen? Are there other errors? Does it actually affect anything?
I learned everything i know from tutorials
is just that i see a guy that does extremely explanatory tutorials (where i learn from) but i never saw him teaching about Raycast
Could someone help me in this? I got an error in the line 14 (marked in the code)
https://hatebin.com/ztavzbmcrh
What's the error?
appreciate it dlich its working
it's down in the code
The error is pretty self explanatory. It says that you already have a field with that name.
I dont find where i have that
oh bro am sorry
damn the dumbest error i had
i forgot to change the variables name
so im trying to switch to the new input system. if i get this right, callbackcontext.performed is similar to OnButtonDown and callbackcontext.cancelled is similar to OnButtonUp?
What line
I'm trying to implement a muzzleflash sprite to be set active when the player fires bullete , but due to me setting false in the same fucntion , it never shows , is there a way for me to activbate and then deactivate once the bullete is shot ```cs
[RequireComponent(typeof(PlayerController))]
public class WeaponController : MonoBehaviour
{
[SerializeField] private PlayerData playerData;
[SerializeField] private GameObject muzzleFlash;
[SerializeField] private Projectile projectile;
[SerializeField] private Transform projectileSpawnPoint;
private float timeTofire;
private Vector3 mousePos;
private void Start()
{
muzzleFlash.SetActive(false);
}
public void Fire()
{
if (Time.time > timeTofire)
{
muzzleFlash.SetActive(true);
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Projectile newProjectile = Instantiate(projectile, projectileSpawnPoint.position, Quaternion.identity);
newProjectile.SetFireDir((mousePos - transform.position).normalized);
newProjectile.SetSpeed(playerData.ProjectileSpeed);
timeTofire = Time.time + playerData.FireRate;
muzzleFlash.SetActive(false);
}
}
}```
can do an animation clip and play once
actually that may still be disabled, so perhaps coroutine then disable
or just dont disable and use an animation play once
okay , i will try an eneumerator
i am super confused with implementing the new Input system. how do i implement button presses in the update instead of its own void? i basically want this, but instead of the normal inputs, the new ones. is that possible?
eg
if (playerInput.actions["jump"].WasReleasedThisFrame())```
thx
what are you confused on?
it would be helpful to start by making a list, rather than an array of lists
You've made an array that can hold 6 lists, but you never made any lists
currently going throught he doc, what confuses me is where the player in playerInput.actions comes from? is that the action map name?
its a reference to the PlayerInput asset
there are dozens wdym
Google๐ช
this thing? so if it has a different name i call it my custom name?
or this thing?
this one
[SerializeField] private PlayerInput inputz;
void Update()
{
if (inputz.actions["Fire"].WasPressedThisFrame())
{
Debug.Log("Fire pressed");
}
}```
yep, works like a charm
why does unity keep outputting "Can not play disabled audio source" in the console, when the audio source its talking about is literally enabled
sounds like it isn't enabled
frustrating af because ive spent the past hour and a half trynna solve this ๐ญ
how? its ticked idek how
prove that the audiosource you are calling Play on is not disabled
show the code where you call PlayOneShot
90% chance you are not referencing the audio source you think you are
i almost guarentee theres more than 1 audio source hiding up in there
at a guess i'd say it's probably a prefab being referenced. or one of the many disabled objects in that scene
also seems complicated having these button and sound pairs
i have 6 audio sources and 6 buttons, Play, Options, and Controls have their own audio sources (empty objects with audio clips dragged into them), and the last four are back buttons for each menu (3 audio sources with the same audio clip)
you should use the context part of the debug to show u exactly which source its referring to..
think i would just have a component on each button that calls some other system to play teh sound
could make it automatic by implement it in the IPointerClickHandler for the click component
^ like an AudioManager static class.. that just plays UI sounds
doesn't even need to static.. could just have a singular gameobject with an audiosource to play all the clips
but how would i specify a specific audio source to be played under specific buttons, if they are all attached under one gameobject
you don't need a separate audio source for each of those buttons though
just one audio source for all of your UI sounds
well if its UI, its not going to be positional audio
so 1 source can be used for all ui sounds
i just wanted different buttons to have slightly different sounds
yes you can sitll do that
but honestly at this point i dont mind having just one, i just want this to work already xD
1 audio source with a script on it, then each button has a play on click component that references the audioclip you want to play
then it can call the system that has the audio source tell it to do a PlayOneShot and pass the clip in
before this it all worked perfectly, but i played audio clips directly, and they were too loud, so i decided to use audio sources to change some of the sound parameters. Now i cant play them
wait let me try this
its so late at night rn lmaooo, but i wanna get this done tonight instead of leaving it to tmr
if you dont have time, would just leave yourself a few notes
public AudioSource clickSounds;
public AudioClip clickUnit;
public AudioClip clickGround;
public void PlayButtonAudio()
{
// Generate a random pitch within the specified range
float minPitch = 0.95f;
float maxPitch = 1.05f;
float randomPitch = Random.Range(minPitch,maxPitch);
// Set the random pitch and play the sound effect
clickSounds.pitch = randomPitch;
clickSounds.PlayOneShot(clickGround);
}```
this is how i deal with multiple sounds with the same function, anytime i click the ground it sounds a bit different..
then i can call other methods that use different clips
but thas just 1 way
If it says it's disabled then it's disabled. It's probably referencing a different audio source than you thought
Debug.Log($"Audiosource played",gunAudioSource);
gunAudioSource.PlayOneShot(machineGun2Echo);
yeah my method is i have a SO type called ClipBucket, which contains a list of audio clips, a volumn range and a pitch range
id just add a little debug to all the places u call oneshot in ur scripts
that way i can easily add varration
they'll be able to be clicked and show which one logs b4 the error
smart
could it be saying that because of my BACK buttons? since they ARE indeed disabled due to them being under different menus that get enabled with a button press. I tried fixing that by delaying the sound playing a few seconds after the entire menu is enabled but that didnt work
yeah all the sound manager stuff for playing sounds will aceept a clip and some args or a clipbucket
the last number on the right is for a weight so can make some more common then others
building ur own tools is magical..
a little extra work at the start.. but so much time saved later
i made something similar
its an audiomanager singleton, that builds itself
then u got all these methods i pre-wrote.. where u can just pass in audiosources or clips as arguments
guys how to make a fading in and out black screen transition between scenes
ur still seems more scaleable lol
yeah pretty similar, audio manager has pools of sources with different settings too
i just make a gameobject with a clip that fades in our out.. and turn looping off..
i just enable/disable it w/e i need
yup, mine grabs the first available one.. and if theres not one.. it creates one plays the sound and removes it..
the garbage collection is probably awful tho
i just animate opacity on a full screen ui image
icl imma just go sleep and come back tmr, thx for your help lads
kk thx
have done a more complex approach for other types of screen transitions like it circle closing on the character etc
but if i just want a fade to black no need to make it complicated
alr thx man
i almost forgot, this is what i was talking about. it's pretty simple: https://hatebin.com/sqyztbrbql
oh, interesting!
void FixedUpdate()
{
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, transform.up).z;
rb.angularVelocity = -rotateAmount * rotateSpeed;
rb.velocity = transform.up * speed;
}
any idea why this doesnt work
it just goes straight up
I'm having problems making an Array for a Unity Object
trying to make a homing bullet btw
and is this for a 2d game?
yeah
what is rotateSpeed
200
well should angularVelocity not be a vector
not for a rigidbody2d
im following this tutorial for it https://www.youtube.com/watch?v=0v_H3oOR0aU
Letโs make a Heat-Seeking Missile that will follow around a target!
โ Download the Project: https://github.com/Brackeys/Homing-Missile
โ Unity Particle Pack: https://goo.gl/2SdCiU
โฅ Support Brackeys on Patreon: http://patreon.com/brackeys/
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท
โฅ Donate: http://b...
since its 2d would be tempted to just do a ATan2 and do the math manually
- not a code question
- you are using a much newer version than that tutorial uses. have you checked to see if you can just create a ParticleSystem object from the Create menu?
i dont know what the math would be lol
I'm trying to make a selection box when you drag your mouse, and I've got code like this
Vector3 mousePosition2 = Input.mousePosition;
selectionRect = new Rect(
Mathf.Min(mousePosition1.x, mousePosition2.x),
Screen.height - Mathf.Max(mousePosition1.y, mousePosition2.y),
Mathf.Abs(mousePosition1.x - mousePosition2.x),
Mathf.Abs(mousePosition1.y - mousePosition2.y)
);
Vector2 min = Camera.main.ScreenToWorldPoint(new Vector2(selectionRect.x, selectionRect.y));
Vector2 max = Camera.main.ScreenToWorldPoint(new Vector2(selectionRect.x + selectionRect.width, selectionRect.y + selectionRect.height));
Collider2D[] colliders = Physics2D.OverlapAreaAll(min, max);
but there's some kind of offset
it doesn't select items that are inside the box
and it selects items that aren't inside the box
var subtraction = targetsPosition - observersPosition;
var myAngle = Mathf.Atan2(subtraction.y, subtraction.x);```
would get you the angle to rotate to in radians
yay! i can save tilemaps now
in the hierarchy not your project window
can convert it to degrees by multiplying it by Mathf.Rad2Deg
like I think I flipped something, because it selects below the box
and above it if I go on the bottom of the screen
okay at this point you've been directed to the correct channel to ask this in. for future reference, when you are trying to get something specific then you need to ask about that.
sure, thanks for the help
is the grid component matched to the unity grid when its 1, 1, 1?
so i found the issue for some reason it doesnt set the angular velocity right it just always stays at 0 the value its trying to set it to works but it doesnt set it
Ohh, so you're saying the issue could be in that I only have 1 castFilter which I'm using for all three collision direction checks?
Wat? A component matched to the grid? Components don't have position, so they can't be matched to anything.
iirc they are referring to the grid component
its mostly used for tilemaps
Aah
though can use it for convert differnet grids coord systems to worldspace and back again
Read the message wrong. My bad.
iirc at 1, 1, 1 and square grid it is matched
but only for that 1 grid type, since you can perfectly match a hex or isometric grid
anyone know why i cant change the angular velocity of my rb2d
Either it has locked rotation, is kinematic/static, or you reset it somewhere else.
i for some reason locked the z rotation lol
im so dumb
And of course there's always the case where you interpret the issue incorrectly.
the grid component,
is setting it to 1, 1, 1 match the unity snapping grid in the editor
ahh you guys talked about it
it simplifies having trigger/collision methods on multiple components. it's much easier to use one component and call methods from others. you can even separate the trigger and collision events into their own components. i made for enter, stay (maybe not), and exit . . .
can anyone know why the hell this funtion not work?
i didnt~~ know~~ think about using events like that w/ the physics calls
you have to convert the value using a log function, IIRC, to get the correct output . . .
nonsense, it is just a float and it also not work
it makes things easier when you break them down to its smallest form . . .
there's tutorials for it. it's a common thing . . .
you arent using volume in your code
also, the parameter volume isn't used at all . . .
dont mind about it, i just write a test funtion with same name
Hey I have a problem with my interface, I've copied and pasted a .cs script from one project to another and for some reason it can't recognize it
Way to confuse D:
you broke it
How do I weld it?
its only 4 lines, copy it delete that one ^ create a new one paste it in and save
make sure the editor is compiling it before u try using it again
Is there a way to attach a script without pasting the code into a new one? 
attch?
This is my code for my player. I have forwardForceX set to -2000, but in my unity it has it set to -5000. Why?
u can right click the interface name and try renaming it thru the IDE
!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.
This should be simple but i cant find a tutorial on this, how can i make a bullet explode when it hits something
Here is the code for my bullet:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float life = 3;
private void Awake()
{
Destroy(gameObject, life);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Destroyable"))
{
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
}
usually that will rename the filename too.. so u can trigger a recompile like that
instantiate a prefab
in ur collision event
that's the default value in your script. once you change the value from the inspector it will always be used . . .
It's like the IAmGood.cs file is there but Unity doesn't see it
!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.
What
heres the code in the website
Renamed the interface then renamed back and nothing 
idk how to force it to recompile
What should I do, I want only th value in the script to be used
its in an editor folder*, not sure that matters either
how can i do this
- to make a prefab u can just drag a gameobject into the project window (the folders)
oh awesome
then u can use https://docs.unity3d.com/Manual/InstantiatingPrefabs.html
to instantiate it at a certain place, or whatever
thank you
maybe the syntax is wrong or something? idk do u have any errors?
thats stopping unity from compiling?
Can somone help me with this, my player is moving at -5000 instead of -2000 like my code
that's not the best option. it's much easier to tweak and change the value from the inspector until you find a value that works properly. you know you can just set the value to what you want, right?
Well, that's the only error it throws, like the script file is there but not included with the project

its in the editor folder.. maybe u need to call the namespace?
using UnityEngine.Editor or is it Unity.Editor
the error says it
thats it, i shoulda asked about errors earlier
Yes I can change it though inspector but idu why Its not working when I have it set to -2000 in the script
-2000 even a valid volume setting?
That doesn't matter if it's an Editor folder
well the error says its in a different assembly
i found the code i used when messing with the audio mixer. don't mind the parameter . . .
public void SetVolume(AudioMixerArgs e) => e.Mixer.SetFloat("Volume", Mathf.Log(e.Volume) * 20);
Its the force
ah nvm, true wrong person
i already mentioned why. that is the default value. when you add the script to a GameObject that value is entered by default. if you manually change the value from the inpsector, it will use the new value because it's not the default anymore . . .
maybe random knows
How do I make it back to default
also, your force value should not be that high . . .
what happened?
his simple interface .cs class isn't being exposed to the script he's trying to derive it from
Why not, and how do I change it back to default
its good in the editor.. but not in the VS, altho it is in an Editor folder, and the error is the *are you missing a using statement.. * error
- reset the script from the inspector (this will remove any values you changed back to default)
- remove the script, then add it back, effectively resetting all values
- or just simply change the value to what you want
i really don't see why this is an issue . . .
did u even try adding the editor using statement?
Now I have this error
it says assemb , - Editor in the thing, so i was almost certain alongside the error, thats the issue
That interface needs to come out of the editor assembly. That's the only solution that makes any sense because they can't build with it in there even if they got the assembly reference
thats probably whats stopping the thing from compiling
why is this interface in an Editor folder? it won't get added to the build, so if you're using it in your game code that'll cause an error. also, are you using an assembly? if so, then you need to add the assembly of the script you're trying to interact with . . .
oh see, i didnt even know that.. soo good stuff lol
I'm trying to learn how unity works, u reset the script and now even my no gravity line is not working?
There's no need to have this interface in the final build, it's just for editor runtime purpose. As on the screenshot earlier I have 2 assemby definitions, one for each folder
It doesn't highlight "MonoBehaviour" anymore
Nvm, so basically every time I make a new variable in the code and change its value ill have to reset the script?
if you're trying to access a class from the other assembly, you need to add it to the current assembly definition . . .
no, you're suppose to change the values from the inspector. you don't set final values from the script . . .
It is added, but even in the same assembly in the Controller class it doesn't recognize MonoBehaviour now
Oh, I understand now..
@vestal ether i suggest following a tutorial to learn how to interact with your code and what the inspector does . . .
How to not strecth the texture for the floor?
Thats what I'm doing. The tutorials are kind of vague on exactly how things work so I got confused.
i'd make sure that your asmdef's are setup correctly . . .
make the floor out of many smaller planes
or
edit the png size
There is a tiling option which I figured out
how can i disable a sprite renderer based on a bool?
spriteRenderer.enabled = false
damn. makes sense
Hey guys, I'm using Navmesh to make it so the npc follows me but for some reason it keeps bouncing off of me as if it's hitting a forcefield. I used stopping distance to make sure it didn't push me but I don't know how to make him stop.
Maybe comment out the translate line.
you seem to be mixing up nav mash motion with your own transform.Translate
That worked ๐ฎ
Thank you
@ivory bobcat Okay so, it's back to do the same thing. Any other suggestions?
i finally found what wrong here
I have a base scriptable object class Item, then one that inherits from it ToolItem : Item. ToolItem has it's own variable that is not on the base Item class.
When I have a List<Item> I cannot access the unique variables on ToolItem even though they can be added to the List.
Something I'm not grasping about scriptable objects and inheritance. I assumed since ant item that inherits from the base Item class can be added to the List<Item> then I could also access the variables unique to each class that inherited from the base class.
wot
You can if you cast it to the type you're interested in, although, that is not a great practice. Can you explain a bit more the context of where and why you need to access the fields of the extending type?
why isn't this working?
I'm just experimenting with scriptable objects and maybe some sort of inventory.
So to make up an example on the spot
- Item type A, B and C each have unique variables associated with them, but all inherit from the base Item class which has the standard variables like name, item sprite, etc.
- Then have all of the items A, B and C in one List or array, then be able to access those unique variables on each for something like a method that scans a players inventory, searches for items of type B, which has a unique variable on it which the method references.
๐ 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.
oh nice
Show your current code
You can find the an instance of a specific type in the list by checking it's type or casting to that type. Then you would be able to access the fields, but generally, you would encapsulate the unique behavior of each sub type within an inherited method, so that you don't need to cast or check types.
For example, if you have a list of usable items and there are many classes that extend the UsableItem class, you would just call a base method item.Use(user) on them and the inherited type would handle it in its own way.
Is the behavior exactly like what it was before?
Make sure to save the script.
Other than that, destination should be relative to player position
So it'd have something to do with player
Did you make any changes since the error had gone away?
This is also the panel
I want to make it where if the player collects 3 keys, a text will pop up on screen saying "You Win!"
So far, my game has collectable keys that can be collected, all that stuff is done with, all i have left to do is make it where if all 3 keys are collected, youll get a message saying "You Win!"
How do i do this? Ill send pictures of my code, and if you want them in text form just say the word and ill send them through gdl.space asap
and if you need any other screenshots or information again just ask and ill send them asap
So instead of unique variables, just have a method on the base item class and then override that on the inherited classes? So instead of trying to read the variables from another class, run the method which can then return that data to the other class that wants the info?
Yes.
There might be cases where casting to the appropriate type might be okay. It really depends on the exact scenario of where you access the object.
How do I remove the turning lock and slippery while turning and the thing where the cow flops?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class DriveCow : MonoBehaviour
{
private Rigidbody Cube_rb;
public GameObject Cube_gameobject;
private Rigidbody Cube_rb2;
public GameObject Cube2_gameobject;
private Rigidbody Cube_rb3;
public GameObject Cube3_gameobject;
private Rigidbody Cube_rb4;
public GameObject Cube4_gameobject;
private float speed;
private float turn_speed;
void Start()
{
Cube_rb = Cube_gameobject.GetComponent<Rigidbody>();
Cube_rb2 = Cube2_gameobject.GetComponent<Rigidbody>();
Cube_rb3 = Cube3_gameobject.GetComponent<Rigidbody>();
Cube_rb4 = Cube4_gameobject.GetComponent<Rigidbody>();
speed = 20;
turn_speed = 2;
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
Cube_rb.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb2.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb3.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb4.velocity = new Vector3(-1, 0, 0) * speed;
}
if (Input.GetKey(KeyCode.D))
{
Cube_rb3.velocity = new Vector3(0, 0, 1) * turn_speed;
Cube_rb4.velocity = new Vector3(0, 0, 1) * turn_speed;
}
if (Input.GetKey(KeyCode.A))
{
Cube_rb3.velocity = new Vector3(0, 0, -1) * turn_speed;
Cube_rb4.velocity = new Vector3(0, 0, -1) * turn_speed;
}
}
}
this is my code
why is he levitating
can someone explain how to use transform direction to me?
It's that a navmesh agent?
What's the actual question?
i am trying to make it so my character moves in the direction i am looking if i press key to move forward
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Aim : MonoBehaviour
{
float yAxis;
float xAxis;
[SerializeField] float Sens;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
Vector3 rotate;
GameObject player = GameObject.Find("Player");
yAxis = Input.GetAxis("Mouse Y");
xAxis = Input.GetAxis("Mouse X");
rotate = new Vector3(yAxis, xAxis * Sens, 0)
transform.eulerAngles = transform.eulerAngles - rotate;
}
}
the aim script
lemme send the movement one
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] int speed;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
speed = 5;
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector3(rb.velocity.x, speed, rb.velocity.z);
Debug.Log("Jumped!");
}
rb.velocity = new Vector3(horizontalInput * speed, rb.velocity.y, verticalInput * speed);
}
}
someone told me i would need to use transform direction
but i cant figure out how exactly do you use transform direction even tho i understand what it does
You probably want to use transform.forward * vertical input * speed, and transform.right * horizontal input * speed to calculate the velocity.
whats transform.forward?
You can check it in the documentation.
My current problem is that the cube goes literally on a direction Vector3.new(-1, 0, 0), instead of moving somewhere like forward or backward or right or left
Cube_rb.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb2.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb3.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb4.velocity = new Vector3(-1, 0, 0) * speed;
OH
so i shall use transform
instead of vector3
that would work probably
as its local space not world space
It's not in any space. Only position vectors can be in local/world space.
how would i use this for sideways movement tho
i am using unity input system
so backwards and forward both is going to be vertical
player
nvm i figured an answer
the char collider is right on the ground but it still can't detect the collission
-_-
What collision? I though the issue was thay it's visually floating..?
i fixed that but the drop sound is still not being called when char collider hits the ground
it only works if i push the player under the ground
@teal viper how would i go around doing horizontal movement?
if (Input.GetButton("Vertical"))
{
rb.velocity = transform.forward * verticalInput * speed;
}
if (Input.GetButton("Horizontal"))
{
transform.Rotate(new Vector3(rb.velocity.x , rb.velocity.y , horizontalInput * speed));
}```
the vertical movement works fine
i think i fucked up a little with horizontal tho
wait why am i using transform.rotate anyway
hi all, I'm new to .NET and unity and I'm trying to import a library from github but I'm getting a lof of compilation errors. I tried googling solutions without much success.
Attached you can find a picture of the repo containing the files i'm trying to get (https://github.com/jfg8/csDelaunay) . What I did is I cloned the project, placed it in the assets in my unity project, then I opened it with visual studio and ran the commands said in the readme, then opened it with unity but got a lot of complilation errors/warnings
Sorry if it's a stupid question, but could someone explain to me how I can import this library in my unity project ?
Then you don't have a collision
You ignore half of my response where I talked about transform.forward and transform.right.
OH MY BAD
i never even noticed transform.right
๐
wait so transform.right is just transform.forward but horizontal?
you can think of transform.right as the tranform.forward, but on the right ๐คฏ
big brain
that moves me forward instead of horizontally
๐ญ
actually no i am dumb
my bad
i wrote transform.forward
intsead of right
again
why not
is there a way to do something like
rb.velocity = new Vector3(verticalInput * speed * transform.forward, rb.velocity.y, rb.velocity.z); (that doesnt work)
so i can preserve the velocity of other directions
making strafes possible
and make it so if the player looks down he doesnt stop moving or if he looks up he doesnt start flying?
Because the sound doesn't play..? Although it's really a speculation without seeing your code/setup.
How could starting a task race against cancelling said task? Also you generally dont need task or async stuff in unity
the debug.log doesn't trigger either
Too many questions at once. Start by solving one problem at a time. First, you should know that you can add 2 vectors.
it only gets triggered if i put half othe player in the ground
I don't know what debug log you're talking about. Haven't seen the code.
Run them on the main thread.
!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.
what do you mean by 2 vectors
And you want to put a log outside of that if statement. How are you gonna know if the method is even called?
like you mean i shall create 2 vector3s
and then put them for rb.velocity
or what?
sorry if i am sounding dumb
thats probably because i am dumb
but alright
2 vectors. Not one vector but two. Like plural.
yeah i understood that
Since transform.forward and transform.right are 2 vectors.
But you want them both combined.
i can do that?
i can use transform.forward and transform.right at the same time??
but then how would i do that
Vector math๐ช
i cant put transform.forward / transform.right in vector 3 tho
Did you not learn about vectors in school?
if theres no log that means theres no collision
i meant how to use it here
How do you combine 2 vectors?
thats why i am asking idk that ๐ญ
Imagine you you throw a ball. How do you get it's velocity vector given you know it's fall down velocity and throw velocity at a given point?
No. That's wrong. What if your condition is just false?
idk i am still in 10th grade
Pretty sure that's covered by 10th grade. If you don't remember, now's a great time to go learn that.
@little garden
no need to keep hopping with the question, didnt get to fully but im pretty sure you can cancel a task no problem before its run. If you're trying to make sure it's not cancelled beforehand, then you need to structure your game beso it's not even possible to do so. Still, not sure what the use case of this is. You dont need to go through async hell for unity
its not false cause when i push the character controller half way through the ground the debug gets called
I learned proper vectors a little later, 11 or 12. Depends on region
So you're fine with it being called when you push it half way through?
new Task(...);
cancel
// task may actually run here
new Task(...)
// both tasks may be scedualed to run but not actually started yet here
cancel
// or here
to ensure the above does not race, would we need to launch two tasks ?
new Task(...) // actual
new Task(...) // monitor
monitor.join(); // ensure actual task has actually began executing
actual task will cancel monitor task when it begins
monitor task will while loop for a token cancellation
I learned them properly when started doing game dev.๐คทโโ๏ธ
Doesn't matter. They can learn it now.
Yea totally, was just saying it's likely they didnt learn it before.
Yea my response still stands, if you have a race condition then I believe you've already started in the async hell
And you can see the downsides of trying to use it in unity
If you're interested in learning vectors properly, Khan academy should have a lot of good videos on it. Im sure YouTube also has a lot since it's a highschool concept. You should be fine with most unity math knowing just the basics which is like magnitude, normalized vector, addition, scaling a vector. Theres more but that's a good starting point
ig\
im trying to ensure an object is only accessed by 1 thread (the thread computing the object itself) while also ensuring such can be recomputed if needed as early as possible
i currently have this https://gist.github.com/mgood7123/878b7c2988372838c51d11ee4fad84c3
You can use mutexes and other kinds of locks/thread safety mechanisms for that. Or just use the unity jobs system and save yourself a headache.
The biggest trick I've ever used, and it is amazing for ForLoops.
If you are working with a static int, and want to see the values for it. Here's an example of how I got to see that value for Health.
public int _health;```
It's a meme in terms of naming convention, but it allowed me to check the conditions regarding a loop that wasn't working, which managed physical heart sprites. And that simple fix, now allows me to get sleep.
All you have to do to initialize it is to use in Start/Awake.
health = _health;
This was essential for a hearts/lives manager system I just completed
Maybe learn how to Debug.Log, or just learn how to use the debugger which is very easy. Let's you view every single value while the code is running.
Learning how to debug is the most important. Also static health is definitely ... questionable
Not for viewing the static int values
That requires you to pair the integer to the static integer, or else you cannot view how that value changes in the inspector.
The lack of seeing static int in the inspector buggggggsssss me, esp when you are relying upon it for loop conditions
There is no pairing needed. You can debug the value anyways. And this value realllllly should not be static to begin with
Do you know how to print something to the unity console?
Static doesn't belong to any instance. It wouldn't make sense to see it in the inspector.
Also this entirely doesnt make sense to begin with. Assigning a non static int to the value of a static one once wont make the values equal at all times. You'll have to change both everytime you change one
I did get a compiler error when attempting to change it to just regular int. Is it less than ideal, sure, but for how my system is set up, it works
you need to know how to reference an instance
You should 100% do some basics of c# before continuing in your journey. This code will be awful for you to edit later
does someone know why I cant add my script as a component to the model that I have, I'd appreciate any kind of help>
Yes you will get an error because now you cannot reference the variable in a static way. Maybe you only have a few references for it. If you try to change this like a month later, its gonna require changes in a lot more scripts
Show the code
okay
it is not done yet, that is the reason why I added /* and */
You probably need to recompile, or save the script. The file name and class name should match as well
Recompile should just be done automatically for you when you save and go back to unity
okay
I am not the biggest fan of my setup even, because it does have ONE side effect function, which annoys me still.
But the setup I had to go with looked like this (which is only part of the three scripts required to make this work)
{
defaultLives = 4;
health = 4;
_health--;
for(int i = 0; i < HeartUiObjects.Count; i++)
{
{
if(_health < i + 1)
{
HeartUiObjects[i].SetActive(false);
}
else
{
HeartUiObjects[1].SetActive(true);
HeartUiObjects[2].SetActive(true);
HeartUiObjects[3].SetActive(true);
}
}
}
if(health == 0)
{
}
}```
i got a test of another subject tmrw ๐ so ima do that later
bool IsGrounded()
{
return Physics.Raycast(transform.position, -Vector3.up, 1.5f);
}
Would this be a routine? Or what do you call this method?
i will call it private method
Do the "if" term at the top and the "else" term at the bottom work together? How can I separate it?
no, it works with second if
But there was a bug
if, else if, else
basic control flow
ฤฐm going to try thanks
Or this
ฤฐ dont understand that
No i dont want work with first if
ฤฐts for normal enemy
You want it to work with both Iโm assuming?
Second and third about faster enemy
Nope
The first one is one piece and the remaining two need to work as one piece
Then change the second if statement to else and put the code in the 2nd and 3rd piece into that else statement
They don't. The first if statement is checked, it it's true, it executes the code inside. Then it continues to the next if statement and if it's false, it executes the code within the else block
Either do
if (...)
{...}
else if (...)
{...}
else
{...}
Or
if (...)
{...}
else
{
if (...)
{...}
else
{...}
}
What I'm actually trying to do is if two enemies collide with the ilede and the booster in place, it should push them back. However, if the player collides with a fast enemy while there is no power-up, the player must move back a bit.
Or you can return early from the first if statement:
if (...)
{
...
return;
}
if (...)
{...}
else
{...}
First suggest doesnt work
Then you have other two
Yea
But they're basically the same, as far as I'm seeing correctly
I think I need to rearrange all the wording
I've used serializefield in my code in order to access variables from the inspector, but the variables are not showing up in the inspector, any help?
!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
Configure your ide, make sure you saved your script and that you have no errors in the unity console
Thanks for help guys
I've saved my script and at the bottom of the IDE it says no errors found, I'm not sure what you mean by configure your ide though?
Sorry yeah I just looked at the links
๐
Check the unity console specifically, not the bottom of your IDE (it may only show errors within your currently opened script[s], not sure tho), but first configure your IDE
I've got the correct one configured, but still not serializefield, additionally I would like to use the newest version, how could I do that?
I have also checked for the errors, I fixed some but I don't know how to fix the rest
They are all on line 52, I have linked it
I don't know why the || isn't working as an or operator, and I don't know why there are expected ; and ), I didn't think they were required there?
Oh ok thanks
And your IDE still doesn't look configured
Did you follow all the steps in the provided link?
I will look through it again, but you fixed the code so thank you
Everything is working, so I think it is configured correctly
Don't think, actually check all the configuration steps.
All the colors in your IDE seem to be messed up (unless you already fixed that) which indicates that it is not configured correctly
Oh really? That is strange. I can't fix it currently as I have to go, but I will save your links and make sure to sort it out later
!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
chat is there a way to do something like
rb.velocity = new Vector3(verticalInput * speed * transform.forward, rb.velocity.y, rb.velocity.z); (that doesnt work)
and uh no i cant learn vector math rn i will try to learn it later tho
i got a test tommorow of another subject
๐ญ
cannot convert vector 3 to float
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] int speed;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
speed = 5;
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector3(rb.velocity.x, speed, rb.velocity.z);
Debug.Log("Jumped!");
}
rb.velocity = new Vector3(verticalInput * speed * transform.forward, rb.velocity.y, rb.velocity.z);
}
}
vertical and horizontal is float
do you have your IDE configured?
whats a x parameter?
so whyd i get that error
transform.forward is a Vector3..
yeah but
No buts
how would i take its value then?
value of what
i basically need to use transform.forward so it behaves according to rotation
but that fucks up the fact that i cant define other velocity
set the rb.velocity to verticalInputspeedtransform.forward
then set the y and z to the before value
forward is the Z axis, and you're putting this in the X axis
its x axis isnt it?
or its not
and i am just dumb
which i am
so makes sense
no, of course not, otherwise I wouldn't have said it ๐
๐ my bad ig
oh just that?
alr ty
i mean i just modify the value like i would modify a normal vector 3 correct?
isn't rb.velocity a normal vector3?
let me try
it's not any special vector3
i might be wrong but will i do
rb.velocity.y = rb.velocity.y;```
no like
2nd part i will replace by old value
but how will i take the old value tho
will i store it in a variable?
cache it before you assign the new one
sorry if i am sounding dumb
ah alr
just think
its not that hard ๐
read it
stop asking question you can just see yourself
no like why is not letting me modify .y
here only
outside i can modify it
nvm i cant
so rb.velocity.x is just a readable term
yup
Vector3 velocityVector = rb.velocity;
velocityVector.y = initialYValue;
velocityVector.z = initialZValue;
rb.velocity = velocityVector;
what can I use something else than transform.forward?
how can I use here Vector3?
what do you mean
you can use whatever you want, it doesnt have to be transform.forward
I've got the same code but a different problem
you can use anything
Cube_rb.velocity = new Vector3(-1, 0.04f * speed, 0) * speed;
@nocturne phoenix
here the problem is that it goes not forward
it just doesnt work
Z is forward, you have Z as 0.. of course it won't move
it does work
yes, it goes up but even if I use
Cube_rb.velocity = new Vector3(-1, 0, 0) * speed;
show what are you doing
but i cant use the values together