#💻┃code-beginner
1 messages · Page 501 of 1
is there any way for a gameobject (not ui) to, on pointer enter, get an outline? the outline component doesnt show anything up for me...
It keeps saying my code has a error
Because a semicolon is a statement on its own
Then you should fix the error
Idk how but I was using a 2yo vid so I deleted the code
if you dont give any details on what youre doing or what error it shows, no one can help x)
Unless it's got to do with render pipeline code or networking, code from 2 years ago is going to be mostly identical
could you post your code here so we can see what's wrong?
It's already gone sorry if I have a new error I will send it
Hi, I'm trying to use OnTriggerEnter2D and having an issue. I want the OnTriggerEnter2D to be called when the player partially exits the area and then re-enters, but it seems that the function is only called again when the player fully exits the area and re-enters. Is there any solution to this?
How would I load an image using relative path to use in an EditorWindow script?
Say if I move the Editor folder, then it wouldn't be able to load the file
Currently I use AssetDatabase.LoadAssetAtPath<T> but it doesn't seem to accept relative path
If they haven't exited, how could they re-enter?
Its just how entering works. Only when you have been out entirely. You could rather check on triggerstay or something and see, how far the position is away from the trigger object or have another collider outside, that checks on enter instead
I just have 2 touching zones and I want a distinct function to happen every time the player moves from one zone to the other, I just don't know how to handle the player going from zone 1 to zone2, then going back to zone 1 before they ever fully exited
like they could just stick their front toe in zone2, then go back the way they came
Could use OnTriggerStay and check if the character's position is inside the collider
Okay I haven't heard of ontriggerstay I'll look into that
If the player is almost entirely inside of zone 1, and dips their toe into zone 2, do you want them to count as in Zone 1 or Zone 2
just an idea: OnTriggerEnter makes the player start Raycasting at its edge furthest from the current zone
It doesn't really matter where the exact line is drawn as long the player can activate zone2, then backtrack to zone1 as i mentioned
but since i was using OnTriggerEnter2D it DOES activate from the toe entering
Can the player be "in" multiple zones at once?
I'd like for it to just count as being in 1 zone
Could also store the zones in a stack.
Enter zone1 -> Push zone1 to the stack
Enter zone2 -> Push zone2 to the stack
(Zone2 is now considered the current zone it's on top of the stack)
Exit zone2 -> Pop zone2 from the stack
(Zone1 is now considered the current zone because it's on top of the stack)
You could make a list of zones the object is currently in, add it to the list in OnTriggerEnter and remove it in OnTriggerExit. Your "Current" zone is the last one in the list
Yeah that
^Yeah, same idea
i want to creat a 2d game like hollow knight 0 experience anyone got tips or a tutorial for me to watch
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ill look into this thanks
you too Osmal
And Faywilds
trying to change ambient enviro. lighting but it is stuck on blue please help :) https://streamable.com/oa2cdp
public void PlayGame()
{
SceneManager.LoadScene("SampleScene");
}
For some reason I cant use the playbutton to go to the other scene. Anyone knows why?
looks like you're missing event system
under UI
And I add that to the Button right?
just the root of the scene
Thank you alot
Confusing why that isnt created automatically on a new scene but whatever
normally does when you add new canvas
can you create a sorting layer for 2d objects on a 3d space? i want my 2d shield sprite to be on top of my 3d player model/.
if urp look into renderer feature
yeah sorry you told me this yesterday
will look into that
i just thought sorting layer would be easier if that existed
It is, it's created automatically when you create your first UI element. The only reason it'd be missing is if you specifically deleted it
I dont think 3D has same sorting order, maybe renderer has one but never tried it 3d, in birp recall having to mess with zbuffer .
if you can mess with shadergraph maybe you can do it there with DepthTexture ? Im not sure tbh this is more shader related
i created a code that should create this text in this panel, but the text get created in an invisible position from the game, the code is:
private void UpdatePlacementUI(bool show)
{
if (show)
{
//set the UI elements when showing
if (placingText == null)
{
placingText = Instantiate(placingTextPrefab, placingPanel);
placingText.GetComponent<TextMeshProUGUI>().text = "You are placing: " + selectedCharacter.UnitName;
}
else
{
placingText.SetActive(true); //show existing text
placingText.GetComponent<TextMeshProUGUI>().text = "You are placing: " + selectedCharacter.UnitName;
}
if (placingImage == null)
{
placingImage = Instantiate(placingImagePrefab, placingPanel);
placingImage.GetComponent<Image>().sprite = selectedCharacter.Sprite;
}
else
{
placingImage.SetActive(true); //sshow existing image
placingImage.GetComponent<Image>().sprite = selectedCharacter.Sprite;
}
}
else
{
//destroy
if (placingText != null) placingText.SetActive(false);
if (placingImage != null) placingImage.SetActive(false);
}
}```
sprite
put debug.log in if statements , check if they are doing what you think they should be
everything seems to work, it all gets created. its just the wrong position
where is placingPanel
i see. Try to pass vector3.zero to the localPosition
if its off you have to check the pivots n rect transforms. Not really code question if its working btw
Need a bit of help with a simple rotation, Currently trying to add a clamp and make it so the rotation doesn't reset with a new button click. It's based on mouse position on screen but the cube resets it's rotation angle based on where I click on the screen
if (Input.GetMouseButtonDown(1))
{
isRotating = true;
startMousePosition = Input.mousePosition.x;
}
else if (Input.GetMouseButtonUp(1))
{
isRotating = false;
}
if (isRotating)
{
currentMousePosition = Input.mousePosition.y;
mouseMovement = currentMousePosition - startMousePosition;
transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
startMousePosition = currentMousePosition;
currentMousePosition = Mathf.Clamp(transform.eulerAngles.x, -45, 45);
Debug.Log(currentMousePosition);
}
Here's an example of what I mean
reading back a single euler angly from the Transform is a recipe for sadness
euler angles are not unique or consistent
you will be much better served by tracking the rotation in your own variable and clamping that
e.g.
float pitch = 0;
void Update() {
pitch += Input.GetAxis("Mouse Y");
pitch = Mathf.Clamp(pitch, -45, 45);
transform.localRotation = new (pitch, 0, 0);
}```
also your use of mouse position and deltaTime doesn't make much sense
much better to use the Mouse Y axis which is a diff, and deltaTime doesn't belong there at all.
Do you mean to replace everything I have with what you put in?
shouldn't that last line be = Quaternion.Euler(
this is in update, when im not aiming i keep setting the showCrosshair to true;
and if i set it to false in another script
would that override?
Is there a way to have 2 overlapping canvases receive a touch?
depends. this is more to do with the order unity is running the scripts. It will probably flip flop so fast it will create weird issues
i did this
so when im aiming it keeps setting it to false
and when i stop aiming it just calls it once
in the AimOut()
Looks like it's assuming a Quaternian already
No. Unless you're using an AND statement. Yes it changes because isAiming is set to true and the HandleAiming disables the crosshair
Setting it to false repeatedly in HandleAiming is pointless, if and only if AimIn() and AimOut() are the only two places isAiming is modified
thats not a euler angle, its says Quaternion right there
quaternion does not reach above 1
Yeah I changed it
btw if u wanna make ur player manager interface nice and clean and spiff you can do:
class PlayerManager{
...
public static PlayerManager Instance;
...
public static void ShowCrosshair(){
Instance.showCrosshair = true;
}
public static void HideCrosshair(){
Instance.showCrosshair = false;
}
which allows you to: PlayerManager.ShowCrosshair(); instead of PlayerManager.Instance.SomeVariableIShouldntCareAboutButHaveToKeepTrackOf = a_value
thanks
oh yeah i can use a static void for this
Looked at the documentation and I'm not supposed to put the new keyword in
technically could also use a static variable since it's a singleton
but that's freaky
Either that or it should be transform.localEulerAngles = new (...)
I'm not able to move the cube with that code anyway if it's a replacement
And yeah no new in front of Quat.euler
oh yeah I added new() mb
yes. You're better off creating a second variable if there's extra state to keep track of.
If another script needs to check "Can the player aim based on something other than "isAiming", then you do if (isAiming and ThisOtherThing)
then you can simply manage the state of isAiming from one place, and ThisOtherThing from the other place
🤔 The value you assign will override the old value.
it works
is there a way to make it so that raycasts don't hit certain objects without using layers? there are raycasts coming out from inside of a car, and i need the raycasts to not hit the collision inside of the car, but i want them to hit other cars.
convert your mouse position to UV-like space, 0-1, then take a section of that space that you want to be relevant and map it to "between -45 and 45"
First thing that comes to mind is to use RaycastAll, then possibly sort those hits by their distance and skip the hits that hit your own car
Could also maybe temporarily disable your own car's colliders but that sounds a bit hacky
i'm not the one implementing the raycasts, it's unity's ML agent packages
can't change the implementation of the raycast
well i guess i could edit the code in the package? idk
project settings
for the record, there is no such thing as "overriding" a variable with some sort of priority or whatever. You're setting the memory slot to a value that is declared. Unless you're trying to modify the value of a variable in a struct after it's been initialized or something, in which case that value is set once and never changed.
Can you edit the car's colliders?
yes
Then maybe this ^
OH nvm the class that unity provides has a field for detectable tags
wait but then i have to create a tag for each car
can you create tags at runtime?
nope you cannot
shoot!
this is definitely what physics layers are for.
Alternatively, you can get all the raycast hits and search for the nearest one that isn't your car?
Or, you can set the start of your ray to be just outside the bounding box of your car (this is probably bad)
i can't change the raycast
Oh I see
Apparently they don't have much control over the raycast
layers wouldn't even work
it's implemented by a unity package
so i can't provide a layermask
nvm it does take in a layer mask
are we talking about a RayPerceptionSensor
oh there you go.
yeah'
but what do i do? just create like 16 tags "Car1, Car2, Car3..., Car16"
you could put the sensors on the outisde of the car :)
don't do this.
you can't
thank god lmao
i'm probably gonna end up putting the uh
the sensor on the object with the car's collision
and i have that one project setting that disallows raycasts from interacting with bodies that they originate from or something
idk the wording
nvm it's a physics2d thing onlyu
how?
like have 4 sensors on each side of the car that all cast forwards? because that sounds smart and i thank you for the answer.
if the sensors are components, stick them on child empty game objects and use the arrows to drag them out or something.
If they all cast forward, I would say put them in front of the car but (?)
i just did this
four different sensors
there you go
it looks like the ML stuff is built for wrapping around a robot interface, almost, with the purpose of simulating agents in a way that it can be translated to IRL
may i ask gameobject problem here?
Basically i want my idle animation stays like that when i click M4
But it wont :(
when i attach my code to the button, i cannot access my functions for reference
Objective = create rightclick aim
but when i put my code in an empty gameobject and then put that gameobject as reference i can??
Yes that is normal. One is the text file itself, the other an instance of the class on your object
Seems like you've got an error in your console. I recommend fixing it even if it comes from another script, as exceptions stops code from running right away, which might cause issues in a related script.
hey im making a top down 2d game and i was wondering if adding overlapping scenes at different scales would be a good way to add depth. the scene you're in always appears the same but everything else scales up or down from your perspective. should i even bother trying to code something like this?
will it still work if i put the code in my parent cube and put that as reference?
Yes, as long as the script you're trying to reference from the button is in the same scene as the button
I figured out my issue. Current Mouse position was based on Input.MousePosition.Y and was moving with Vector.right (X-axis). I no longer have a weird jitter now
I did not figure out my issue after all
he's trying to get it to maintain the animation after clicking off the animator
often times I have exceptions because of editor bugs that can be ignored
little things in editor gui's and stuff that never show up again (8
Yes that's how that works
The stack trace isn't visible so I can't assume that's the case
But without seeing the full error, we can't just assume that. A Null Reference Exception can and will brick an entire script
i was crying qbout the calculator 2-3 days ago
turns oout that was the issue
Okay, now I've found out my issue. I need to do some clamping now
how do i change the gravity strength of an object in 3d
- add downwards force every frame
- project settings -> physics and set gravity
- Use the ConstantForce component to do 1 without any code.
depends on what you are using
I keep forgetting that thing exists
I really should use it more
its for my player, he kinda just slowly floats downwards
are you using a rigidbody or character controller
rb
then do what either praetor or naeve said
That and the XXXConstraint components are hidden gems
I have gotten used to those, it's one of the few whitelisted behaviour components for VRChat and is great for making effects and things
is add force (the impulse mode) bad for 3d?, my character kinda just teleports upwards
the teleportation is a side effect of the combination of:
- Using too high a force
- Haveing other code that overwrites the velocity
even if i use a low force it teleports up just a shorter distance
because of the second point I made
but no other code overwrites the velocity
show us the !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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerJump : MonoBehaviour
{
public float jumpForce;
[SerializeField] private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce, 0, ForceMode.Impulse);
}
}
}
This is not your movement code
this is only jumping code
oh it needs to be in the same code?
I didn't say that
I just said you have other code that is overwriting the velocity
Likely that's your movement code.
show us your movement code
Yes, I've seen this many times
i will fix it
thank you
what does quaternion.identity do btw i saw something about it, is it just a fancy way to say 0?
use documentation for these types of questions
Yes, that is what it means (basically like Vector3.zero)
thank you
Hi
how to make converter of string to cetrain-characters-lengthstring?
(it cuts my string if it longer than 7 characters or add spaces if initial string is shorter than 7 characters) please?
Just make a function that checks the length... if it's too short it adds padding - if it's too long it calls substring.
(yeah using the two functions Sidia linked)
thanks
wait why does GetKeyDown not work in FixedUpdate again?
Because it can be skipped during a frame.
Update runs every frame, fixed doesn't guarantee it.
ohhh okay thank you
is this way of doing this?
SetFOV will be used in update in other scripts
so i want to automatically set useNormalFOV to true if the SetFOV method isnt being called
What are you trying to achieve with this?
in any script i want to be able to call a method where i pass in the fov i want and the duration to achieve it
and if the method isnt being called then run the logic in the UpdateFOV
useNormalFOV is going to be true at the start of every frame, and become false once the first thing calls SetFOV, which means that UpdateFOV will skip if it's called after one of these
So, first off, nothing prevents multiple things from calling SetFOV every frame and fighting it out. If you want the UpdateFOV to happen after everything else has updated, you should probably put all that functionality in LateUpdate
Right now, it would sometimes be called before SetFOV is called, sometimes after, which is going to be inconsistent
Probably better to have a script that allows you to set the target and time remaining, then have that function just always smoothdamp towards the target FOV. When the timer reaches 0, set the target back to the default FOV
That way if something else adds in a new FOV target, it'd also reset the timer to a specific value and smoothly move towards that new value
So I have this object placed on a custom grid. I would like to find the height of the object, specifically within a grid position, not for the whole object. So for example, the leftmost gridpoint would have a height of something like 1, but the height of the rightmost gridpoint would have something like 2. How would I do this?
Currently entertaining the idea of raycasting from the grid position, but curious to hear what others think.
Something like this:
void Update(){
cam.fieldOfView = Mathf.SmoothDamp(cam.fieldOfView, currentTarget, ref currentZoomVelocity, timeRemaining);
timeRemaining -= Time.deltaTime;
if (timeRemaining <= 0) currentTarget = originalFOV;
}
Keep track of the highest point of the object overall.
Boxcast with the exact width of a grid cell, centered on the grid cell, originating at the highest spot plus the thickness of the boxcast plus some small ofset, cast downward from above. Get the world position of the contact point, subtract the world position of the ground, the Y value is your maximum height of that cell
Makes sense. What about if I want the average height in the cell instead? Dancing between that and the output of your idea
Stupid question but where did the shape come from? Is it created by the user or premade? If premade you could bake this info into the prefab somehow
Hm... that's a lot more interesting. I'm not entirely sure, I'll have to ponder that a bit
Just something I cobbled together in probuilder.
Okay, same deal, but instead of a boxcast, you want to do an array of evenly spaced raycasts across the grid cell. Higher count gives you more accuracy, but at the cost of performance. I'd say probably at least a 5x5 grid of raycasts. Then you'd get the distance of each cast, and average the height computed from each.
Also makes sense. I wonder, why not raycast from the grid position upward until the raycast no longer collides with the obstacle above the grid position?
There's not really an "anti-raycast". You can't detect when a raycast stops hitting something, it hits one thing and then ends
That's why you'd need to cast from above and cast downwards
Ah ok, makes sense. Sounds like I have a plan here. Appreciate it!
Also, with layermasks, you can absolutely skip the "compute the highest point and cast from there" step, you can cast from way high up as long as you're sure the first thing it'll hit is what you're looking for, which you can do with a layer mask that excludes other stuff
is there a way to restrict enum options in the inspector based on a condition? like, you cant do animation A if the object isnt far enough away from the top boundary in like a box of rigidbody/box collider objects
You could use OnValidate to check for this logic
Hello, Im trying to add Actions of players. on click just punch but if clicks and hand collider touches object with resource tag then get resource.
I have this script added on Hand of the player.
public string isHolding;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Resource")
{
Debug.Log("touched Resource.");
}
}
I just want to know if going like this is a good practice, or what would be best practice which will be easy to modify later in a code.
I just want suggestion on how is a good way to make this mechanic. (stuff like if player is holding something then do this or if player hits resource then get resource if player hits enemy then deal damage etc.)
I doubt I'm going the right way because I have PlayerAction script added on Player's hand.
This kind of interaction is usually much easier to do with a direct physics query instead of waiting for a trigger callback
i.e.Physics2D. OverlapCircle/Capsule/Box
you can do that directly in the "punching" code without having to wait for a callback etc
Alright I'll make the punching script right now and try that.
also, should I put punching script on the player's hand or on player itself.
Most likely the player
also where would I find this Physics2D overlapCircle and those example codes or documentation, I don't know how to exactly write code for that so
!docs
I usually use google instead of the doc's own search
also how would I uh... find every resource's points?
wdym by "find every resources's points"
You would check at the position you are punching or whatever
it will tell you which object if any you hit
A layer mask would be better
alright so layer mask.
and a TryGetComponent
but yes you could use tags
a combination of layermask and either tags or TryGetComponent is typical
also how would I make that overlap only check this part.
By this I mean, I see radius and point so
Use OverlapCapsule if you want that, since that's a capsule shape
no
it will find any collider contained in the given layermask and position
ok well how do I get specific point atleast
so I might build up other code on it I just don't rly understand how I can implement it now
like what vector should I put in the point parameter
and also what direction im putting here?
Try using the transform.right or .up of your arm object
so connect my arm to the script first right
Physics2D.OverlapCapsule(playerRightArm.transform.position,new Vector2(4.5f,9f), playerRightArm.transform.up);
So will this work?
(I know i have to add other parameters too)
oh, it doesn't work
Forget this^
From that page you can see that direction is a member of CapsuleCollider2D
Physics2D.OverlapCapsule(playerRightArm.transform.position,new Vector2(4.5f,9f), playerRightArm.GetComponent<CapsuleCollider2D>().direction, 0);
And its type is CapsuleDirection2D
It pretty much says everything there is to say about it
Need to use the arm's angle instead of 0
Should I put 7 in that parametere?
what about this
ok I'll remember that thanks
Good thinking, but not quite. You can't use a layer as a layermask directly
You can use LayerMask.GetMask to get a mask with that layer
new Vector2(4.5f,9f),
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));```
I also want to add animation where collider going to move on left click ofc, so I'll create animation right now.
also, I can do something like this?
Yeah, that's the same as doing if(collider != null)
Usually you can't but Unity made so that any UnityEngine.Object (colliders, components, monobehaviours) can be used as a bool to check if they exist
Didn't quite get result I was excpecting...
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Punched");
//Left-clicked
//punch logic.
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
new Vector2(4.5f,9f),
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log("Collided with resource.");
}
}
}```
I get it thanks
Idk what to look at here
debug log
Btw why use new Vector2(4.5f,9f) when you can just use the collider's size
Basically I was excpecting to get Collided with resource when touching a resource
yep changed it
This
ohh i see its at top
Basically I wanna create punching.
and your Resource is tagged correctly? no misspellings
I do wanna add it so it will be easy to modify later on when I add swords or something
I'll recheck
LayerMask.GetMask("Resource"));
Make sure that the child collider has the right layer too
oh true true
what child collider
if there are any
ye no there aren't
Maybe it's on the same object
some people use a structure like
- Object
- Colliders
- Graphics
that why we typically will include asking that
Yeah but you don't need to in this case
mmhmm..
ok so what maybe causing this
Maybe phys2D doesn't hit triggers by default?
can u log all the collisions and check if its colliding?
Try setting this bool to true before doing the overlap: https://docs.unity3d.com/ScriptReference/Physics2D-queriesHitTriggers.html
I remember the tree's outer collider being a trigger
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Punched");
//Left-clicked
//punch logic.
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z
/*LayerMask.GetMask("Resource")*/);
if (collider)
{
Debug.Log("Collided with resource.");
}
}```
it did work like this
But I'm not sure if that bool is true or false by default (Unity pls add default values to docs)
should I use tag?
Try that but log the collided object's name also
should I do it in start() ?
Debug.Log("Collided with resource: " + collider.name, collider);```
u could do it directly before the call
im using $ more often
good
You can use that, I was just avoiding extra confusion lol
string interpolation is the beeeze neeeze
facts.. lol
no im good with c# xd
just don't know unity lab
we can't always assume people know what string interpolation is..
then its just an extra conversation
I'm also not american so I have a small delay when trying to find the dollar sign on my keyboard 🤦♂️
But Debug.Logs like these are temporary anyway so performance doesnt matter
im not american so I have a small delay choosing words I should say
alrighty.. now we're getting some data
Wish I could do using € = $;
get ur drunken E, C wannabe outta here
i heard something the other day about "symbols"
i didn't get a chance to read up on it.. but it seemed something similar to that
Math symbols or something another
I did see a heated conversation about symbols yeah
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Physics2D.queriesHitTriggers = true;
Debug.Log("Punched");
//Left-clicked
//punch logic.
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"Collided with {collider.name}");
}
}
}```
works now I think, now animation time.
welp, good work homie
will animations break the code? (I will also animate collider so will it work like that?) and also how would I add animation so like when it clicks left click animation plays.
How much wood could a wood chuck chuck if a wood chuck could chuck wood?
wood
the animations (if affecting the colliders) will change the start point of ur overlap
Why didn't it work before? What did you change
added that thing u told me
but I just realized one more problem.
like it may be better to find the origin starting position of the arm
and get ur overlap from that
So the tree has two colliders.
Oh the querieshittriggers bool?
instead of using the arm's actual position
It only detects if I touch inner one.
yes
ahhh soo it was a trigger
I might leave it as arm's actual position
i missed that info
I only knew it was a trigger because I helped Qvabbyte implement "squishy trees" the other day
I called it smoothnes behaviour idk why xd
like squash and stretch?
Nah, just softly colliding/pushing out of the tree if you stop in it
ive never been inside a tree
try
Well we could say "under" the tree's branches
gotcha makes sense
well, find the colliders center point..
and then range?
Wait so it still doesn't detect the outer collider (trigger)?
interesting
only inner collision
Show the inspector of the tree with both colliders and layer visible
ok no
it does.
Im tripping wth
I just couldn't really realize because
When i tried to collde
well we have a script on a tree for that squsihiness right
which pushed me out before I clicked.
so it does work, I'll just make hand collider larger.
What did you search
renderer urp unity docs
I think it doesn't work when the animation plays...
Yeah because you are only checking it once when you click, right?
yes
{
if (Input.GetMouseButtonDown(0))
{
animator.SetTrigger("Punch");
Physics2D.queriesHitTriggers = true;
//Debug.Log("Punched");
//Left-clicked
//punch logic.
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"Collided with {collider.name}");
}
}
}```
You can either use animation events to trigger the check from the animation
Or start a coroutine when you punch and check it for a few frames
So put everything after the SetTrigger into its own method and use either of the above to call it
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
animator.SetTrigger("Punch");
checkCollision()
}
}
private void checkCollision()
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"Collided with {collider.name}");
}
}```
There u go
anyone know why im getting this error?
Thinking of coroutine, it might detect collision like 100 times in that animation, I don't want that. I wan't it to detect one but with animation too.
or will it
like should I stop coroutine when it detects the collision?
Something is trying to load a scene that isn't in the build index. Check the stack trace to see if this is actually the problem
mk
Sure
And you have full control of how often it checks
How would I do that tho xd
Coroutines are a way of performing an operation over time instead of instantly. They can be useful, but there are some important things you need to be aware of when you use them to avoid inefficiency in your game or application. By the end of this tutorial, you’ll be able to: Explain what a coroutine is and how they work. Determine when it is a...
i need to refactor some of this code so more is not done on update else performance is going to die now i need to remember how to set up events
because i dont think its a good idea for me to update my ui every frame Especially as that UI is just for seeing if i can interact with something but then again idk if events is what i need as it constantly needs to check the overlaps sphere to see if i can interact with something
i got this so far
how can i access the Field Of View?
i got a reference to both of the render objects
but there isnt a .overrides
Is this valid?
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
animator.SetTrigger("Punch");
StartCoroutine(CheckCollision());
}
}
private IEnumerator CheckCollision()
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
StopCoroutine(CheckCollision());
}
else
{
yield return null;
}
}
can I like stopCoroutine inside coroutine?
So, play through this in your head, assume you can. If you press 0, you start a coroutine. This coroutine does a raycast, and if it hits, you stop the coroutine. Otherwise, you wait a frame and then stop the coroutine. Does that actually do anything?
yield return null; waits a frame and stops coroutine?
It waits a frame then continues with the next line
There's nothing after that
so the coroutine ends because it just runs out of things to do
How about this then.
Recursion
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"You pucnhed a {collider.transform.name}");
StopCoroutine(CheckCollision());
}
return CheckCollision();
}```
hell no xd
Does that compile
ofc no
it loops
You need to know what a coroutine does. When you start it, it runs code as if it were an ordinary function, until it hits a yield statement. When it does, it waits for whatever condition you're yielding for, then resumes where it left off
So, at what point do you want this to pause, and for how long
and what do you want it to do after the wait
yeah but how could I make so the as long as animation runs don't stop coroutine
Like start the coroutine as animation triggers and stop the coroutine as the animation ends.
Hint: a synonym for "as long as" is "while"
does animation have like bool kind object which indicates that animation is running?
So, you want to repeat this raycast every frame as long as you're in a specific animation?
yes
coz if yes I can do while
So, maybe while the animation is a specific state, you'd want to do the cast, and then wait a frame
yeah sure
So, do you know how to check if the animation is in the specific state?
is it animator.isActiveAndEnabled
noo
I was reffering to if animation is active question
That would check if your animator component is enabled and the object it's on is active
like if component is disabled or enabled?
Yes. Is that what you want?
its in the build index and no matter what i tried i cant find stack trace
That's what digi is talking about. An animation state is the thing that holds your animation clip in the animator*
if animator disables itself and enables only while animating then yes
So, might be worth looking up how to check for a specific animation state
Click on the error in the console and show what comes up in the bottom window
same thing the error said
Okay, so the error is in some networking code called by Launcher.cs line 137. What is that line
the highlighted line
do
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"You pucnhed a {collider.transform.name}");
StopCoroutine(CheckCollision());
}
}
while (animator.GetCurrentAnimatorStateInfo(LayerMask.GetMask("Default")).IsName("PlayerPunch"))
yield return null;
so here is what I came up with
So, it looks like Photon doesn't like that build index. Since you've literally gotten it from the active scene, it doesn't seem to be something wrong with your code, it's something wrong with your configuration. #archived-networking would probably know what you'd need to do to get photon to have the same scenes.
Why a do-while?
ok, ill go ask there
By the way, the way to stop a coroutine from inside it is yield break
Actually do-while is not too bad here
it does give me the Invalid Index on layer thing.
You can skip the first check since you already know it's playing when the coroutine starts
In most cases, either one will work, but I'm wondering what the thought process is. Because unless you know why you're using a do-while, you probably shouldn't
Yeah but I realized that this is actually a decent use case for it
But true, there should be reasoning behind it
Then LayerMask.GetMask("Default") is not a valid animator layer. Makes sense, since they have absolutely nothing to do with each other
Yes, that is asking for the animator layer you want to check
Its on baseLayer
wait I'll check how do I check animator layer
So I have another problem, I'll send video guys.
public GameObject playerRightArm;
public Animator animator;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
animator.SetTrigger("Punch");
StartCoroutine(CheckCollision());
}
}
private IEnumerator CheckCollision()
{
do
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"You pucnhed a {collider.transform.name}");
StopCoroutine(CheckCollision());
}
}
while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"));
yield break;
}```
problem is... It doesn't work.
Seems to be working fine?
You are getting the log when you hit the collider
Again, why do-while
Collider is larger then u think
I don't know I just didn't really think that in this case it would make a much of a difference
It'd be easier to see what the code is actually doing with a traditional while loop
It's touching the renderer but not the collider here
no I just showed u that the hand collider was large, Wait I'll show u better video
or no
take a closer look at debug log
im standing really close
not getting even when the collider thing turns more green (which I think means that colliders collided)
and I think
Wait your while loop doesnt even have a yield statement in it
While crashed my unity just now
Please just switch to a while loop at least while we debug this
when I switched to while from do while
Instead of doowhile
Well, you have no exit condition. If the collider doesn't hit anything, the animator isn't going to change if you're stuck in a while loop
Because you aren't letting it wait between the loop's iterations
Also, you're still using StopCoroutine instead of yield break
ok fixed that
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"You pucnhed a {collider.transform.name}");
yield break;
}
}
yield break;```
Notice how the "and then wait a frame" is inside of what I said you should be doing while the animation state is the thing you were checking for
Oh I missed it, my bad.
yield return 0;
right?
while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"You pucnhed a {collider.transform.name}");
yield break;
}
else
{
yield return 0;
}
}
yield break;```
or not in else
You say "and then wait a frame"
did u gave me a hint on how I would write the code or hint on what I would search next xd
yeah this doesn't work
it does but doesn't
Are we even sure that the animation state changes instantly?
If not, it will just skip the while loop and go to yield break
so if I click rapidly fast I get log but if I click like slowly I don't get any response
You already wrote it in the first coroutine. You waited a frame and then the function ended.
yield return null
Yep. That's how you'd wait a frame.
0 won't work?
Unsure, but even if it did, there's no reason to use that instead of null. Less garbage generated that way
Try waiting a frame before the while
Ok
crashed.
private IEnumerator CheckCollision()
{
yield return null;
while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
{
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
Debug.Log($"You pucnhed a {collider.transform.name}");
yield break;
}
}
yield break;
}```
Where'd your else go
I deleted it
why
because thats where yield return null was at
and If I moved that before while
what would else even do
I never said to remove the one in the while
Remember what I said up here. Read this, internalize it, and then go through your code with this knowledge in mind to know what it is doing
Remember that only one line of code can ever be running at a time, and a frame cannot end until every line is run
ayyy it works!
So, if you don't have a pause in the while loop, the frame cannot end, so the animation cannot update
so frame waits while loop to finish
if while loop doesn't have a pause?
so that's what our else does in the code, it pauses.
The definition of a "frame" is "However long it takes for every object's Update to finish"
Combine that with what I linked, when you start a coroutine, it runs that coroutine until it hits a yield
but how did the first yield helped it
When it hits a yield, the coroutine pauses, and the code goes back to where it started the coroutine
like yield before while
Because the animator hasn't actually changed the animation yet
Waiting a frame first means it has time to actually change
So we wait before animation changes, then pause by each frame till in that animation at some point collider touches or else just end the coroutine
so we basically check if collider collided in each frame of animation's state right?
Yes, you start the coroutine, then immediately hit a pause, and then finish out the frame. Next frame, it resumes with the next line, that starts the while loop. Either you exit the coroutine, or you pause a frame and check again
Ok so this would be detailed info right.
private IEnumerator CheckCollision()
{
//wait for animation to run
yield return null; //<-- wait a frame.
//while animation is in punch state.
while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
{
//Check if Collided.
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
//if it did stop the coroutine
Debug.Log($"You pucnhed a {collider.transform.name}");
yield break;
}
else
{
//if it didn't wait a frame.
yield return null;
}
}
//if animation ended and still didn't collide.
yield break;
}```
You can remove the last yield break, coroutines automatically end when they run out of code
Topdown camera, the mouse is on the yellow star, how do I always get the red X position no matter what the camera rotation on y-axis?
raycast, then add camera.transform.up?
Ok, thanks for helping!
I want to make a name system that always display the name of the units on their heads
the camera can rotate freely
is worldtoscreen the proper thing for this?
nice, it is
How about this tho.
private IEnumerator CheckCollision()
{
//wait for animation to run
yield return null; //<-- wait a frame.
//while animation is in punch state.
while (animator.GetCurrentAnimatorStateInfo(animator.GetLayerIndex("Base Layer")).IsName("PlayerPunch"))
{
//Check if Collided.
Physics2D.queriesHitTriggers = true;
var collider = Physics2D.OverlapCapsule(playerRightArm.transform.position,
playerRightArm.GetComponent<CapsuleCollider2D>().size,
playerRightArm.GetComponent<CapsuleCollider2D>().direction,
playerRightArm.transform.eulerAngles.z,
LayerMask.GetMask("Resource"));
if (collider)
{
//if it did stop the coroutine
Debug.Log($"You pucnhed a {collider.transform.name}");
CheckAnimations(collider);
yield break;
}
else
{
//if it didn't wait a frame.
yield return null;
}
}
//if animation ended and still didn't collide.
yield break;
}
private void CheckAnimations(Collider2D collider)
{
if (collider.transform.tag == "Tree")
{
collider.transform.GetComponent<Animator>().SetTrigger("GotHit");
}
}```
You can remove the last yield break, coroutines automatically end when they run out of code
Fixed it!
no i mean
that didn't fix it
I fixed it I had problems with animator itself.
had to remove exit time.
hello! i wanted to use unity 6 for my next project but was wondering if its stable? like i plan on making "game jam" like games (something simple to mediocre nothing too big)
would yall recommend that I stick with lts or can i use unity 6 preview?
id assume the preview is prone to bugs? idk i havent been keeping up to alot of the news so
isn't it still in preview
preview stuff is not truly meant for production
ah oke
o nah just wanted to try the latest features lol - no actual reason behind needing to use it
so i kinda just wanted to make sure if unity 6 preview can be used for production just in case haha
I don't think you'll encounter any of the "new features"
Hello, Im new to Unity. I making a small game and i want text to pop up after a collison happens (aka, my character running into another character). Im having troubles getting it to work. i dont think the collsion is being detetced. Im completly stuck ):
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
@astral falcon @languid spire Just to circle back, I much appreciate the help. My dumbass thought the only debug was the script debugger not the inspector debug as well (which was my issue). Thanks again 🙏
Is there a way to make Character Controllers ignore collisions? Using Physics.IgnoreCollision(), Physics.IgnoreLayerCollision, and setting layers to not interact hasn't worked work
Rigidbodies on the same layer do not collide with each other but still collide with Character Colliders on the same layer
Using Physics.IgnoreCollision() with a Character Controller and colliders without a Rigidbody work
Ignore collisons in what sense? Like when you call Move on the CC? Or for other objects bumping into it?
Calling move on the CC
Calling move on the CC has nothing to do with normal physics collisions
it's essentially dooing a capsulecast
if you don't want such collisions there's no reason to be using a CC at all
disable the CC and just move the Transform directly
I have platforms that can ignore the collision of the CC that work with Physics.IgnoreCollision()
But when I do the same with 2 CC's it doesn't work
because CC.Move doens't use normal physics collisons, as mentioned
Okay that makes sense
So there isn't a way to have 2 CC's ignore only each others collision
Without working around and just disabling them both
Hello, I beginning in C#, I’m from Python, is there an equivalent for this instruction
l = [0,1,2,3,4,5]
newList = l[0:2]
# >> newList = [0,1,2]
= l[0..3]
if i were to make a crouching system, would it be best to simply have it where when they click whatever keybind i have chosen for crouch, it just moves the camera?
is that the primary idea behind a crouching system for movement or is there more?
if you want a shallow copy of a section in the list then you can use var newList = l.GetRange(0, 3);
For a single player first person game with no legs visible that would be sufficient
But collider will not move along with camera, if you use physics you will have to handle this
ig you could simply shrink/extend its bounds on state changed
i have this code but the bullet wont move
same code worked for the player but when i try to add to enemy it doesnt work?
because you are setting velocity on the prefab not the instantiated object
Physics.RaycastAll -> what is the proper way to order all hits in the order they've been hit? why isn't it ordered like that by default? I'd like the first detected collider to be [0], the second one as [1] etc
You'll have to sort the array by the distance property. It doesn't do that by default because sorting is expensive and if the order doesn't matter it's actively harmful
just sorting by distance would do the trick?
That would sort them from closest to farthest relative to the starting point
but i'd need to sort based on the hit.point rather than the collider position itself, right?
Distance is to the hit.point
If you want to sort to the collider position then use that instead
hitInfos = hitInfos.OrderBy(hitInfo => Vector3.Distance(playerPosition, hitInfo.point)).ToArray();
so i guess that should be enough
Raycasthits already store a distance
Sure but you're re-calculating the same info that's already in hitInfo.distance
oh ok
so just hitInfos = hitInfos.OrderBy(hitInfo => hitInfo.distance).ToArray();?
thanks
How are you using that array btw?
If you are just iterating over it then you can leave it as IEnumerable, no need to convert to array
Generates extra garbo
You can remove ToArray and it will work
perfect, ty
wait, are you sure?
because RaycastAll returns RaycastHit[]
i guess i just cannot do hitInfos = orderby...
just only hitInfos.OrderBy(hitInfo => hitInfo.distance); without hitInfos = (...)
well, without ToArray() it doesn't work properly, with ToArray() it works
It works, you just can't assign it to an array variable (hitInfos)
You can do var ordered = hitInfos.OrderBy(...)
And then do a foreach on ordered
Extra array allocation avoided 👍
OrderBy is a LINQ method, and these always return an IEnumerable. The reason why it doesn't work is because the variable expects an array. That's why assigning to a new variable works.
And FYI, IEnumerable exists to be iterated. It's a special type, and in your case since you only do a single iteration it works just like the array
However, make sure you don't iterate it multiple times
no i dont
If you do this, OrderBy is called multiple times too
In that case you should just ToArray() again
i just have 1 loop, once i find first valid collider for my use case i return
and that function triggers only when i shoot
Then it's all good, just keep in mind an IEnumerable will invoke all the LINQ methods that defined it when you iterate it
interesting
I thought that it would only order it when you actually call OrderBy
but it also invokes all "cached" LINQ methods
when iterating over it?
You basically store this method until you iterate the IEnumerable through the foreach, or with ToArray()
You can do this yourself. Make a method that returns IEnumerable<T>, and inside you can use the yield keyword
ahh ok i think i got it
This method will be an iterable method, and it will not invoke until you iterate it
It's hard to explain. Unity Coroutines work the same way
Yeah IEnumerable methods are pretty powerful
And learning them made me realize that coroutines aren't "black magic"
No need to understand how quaternions work internally, just learn to use the helper methods: FromToRotation, LookRotation, AngleAxis, Euler etc.
yea I do know them
If you ever wanted to understand them a bit more, you can just forget about all helpers besides AngleAxis and operate on normalized Vector3 directions
(Its just one way of learning, may not fit your preferences but worth trying imo)
Or just use docs 😁
This is the other way of learning. Not fitting my prefs xd
As much as people hate when I say it, it's true the documentation will tell you what it is, how it works, and how to use it.
Although a bit tricky at first since nobody knows where they are lmao
Agreed. But for some people like me theoretical explanations even backed by examples aren't always sufficient. I like to visualise things for example having 6 gizmo rays (describing 2 different direction vectors) and runtime see what is happening using AngleAxis. Basically you can recreate any other helper method with it
Oh yeah 💯 if you can visualize something, best go for that since you will actually see what its doing so your not guessing.
Using Handles would also help with visualization, but I haven't grasped and good handle on them yet
That was not supposed to be a pun, but I wish it was
Oh... There is such thing o_o
Yeah, just checking docs about them. Apparently it's just faster an more customizable way of doing 6 rays 1per axis
When I saw you can use them to display text above objects I was intrigued
Neat. At least for large teams
Ah I wouldnt say they are solely for large teams, they can be used by a solo dev with practice of course unless they want to get a project full of errors, this concept applies to anything.
Well yeah, didn't express myself precisely. I mean it is good for everyone, especially large teams
Of course mb
Like it's a bit must for them ig
dont know, if this belongs here. i hope so
I have question, what does this corountine do? Never seen this syntax anywhere.
you mean the StartCoroutine ?
yes, it's basically unnecessary.
assign the return value and throw it away. totally pointless
what concerned me was OP asked about the coroutine which displays a lack of understanding of the whole situation
#🔊┃audio Next time actually try to look for the correct channel
yea i asked for full line. that _= and that startcoroutine too.
depending on who you ask it's considered to be a good practice to assign the result to a discard variable if it's running something async and you don't care about when it's going to finish
then it's clear that you simply didn't forget about waiting for the results, you simply don't care
this is mostly used for Tasks though, although Coroutines are pretty similar in that regard
the StartCoroutine is just starting a coroutine, an asynchronous operation
instead of the discard you could write it as yield return StartCoroutine(WaitAndRecalculate())
then it would wait for the async operation to finish and continue execution in the next line
You can configure VS to warn you by default if a return type is unused and not discarded. I have it onby default
okay this isnt a unity question but just a general c# question, why the hell do I get this error in my if else
its saying it expects a ;
in my else?
that doesnt make sense
Where's your if?
else can't have a condition attached to it
only else if can
If you write just else then the next thing better be a { or the start of a statement. You can't have a condition on an else.
not only that but you are re-declaring itemCost in every one of those blocks
none of them actually change the outer itemCost variable nor what you are returning
this seems like the perfect use case for a switch statement:
public decimal GetItemCost() {
switch (itemCost) {
case 1:
return 5.99;
case 2:
return 19.99;
//.. etc
default:
throw new Exception($"Unexpected itemCost value {itemCost}");
}
}```
i would use that, but this is for school so i have to use if statements. I did figure it out, but yeah I genuinely am so lost on how to do this program and its probably the most simple thing ever
You still have major issues with the structure of your return statement and your variable declarations. But yes the key point here was you tried to attach a condition to else which cannot have a condition
man i wish my teacher was better, this is miserable trying to learn it on my own
basically the code i have to do is to enter in sales info, and there are 5 items with different prices
so im trying to use an if statement to return the correct value for which item the user inputs
You've overcomplicated it a bit
thats what it seems like
it's as simple as:
public decimal GetItemCost() {
if (itemCost == 1) {
return 5.99;
}
else if (itemCost == 2) {
return 19.99;
}
// and so on
else {
return 0; // default for when we don't know this number?
}
}```
this is the rest of my code, based mostly off of the "skeleton code" we were provided
that seems so much easier, damn
unity doesn't use Console class
would this make it so the code that is ran in GetItemNum() would be used within the if statement?
I strongly suspect this isn't Unity honestly
I have no idea what you mean by that question to be honest
seems like general !csharp
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
thats what I needed, thank you I was only in here so i thought id give it a shot
thank you for the help nonetheless!
can you get the key of a dictionary using just the value the same way you get a value using the key?
Not easily
its not reversible?
You could loop through all of the keys, then check if the value of that key is the thing you're looking for. But if that value is in multiple places you won't always get the same one
i'll just reverse the dictionary f that
The values aren't unique so you'll possibly get conflicting data.
its fine then, for my case i can just reverse the dict
any idea why it prints the particle which is called bullet, is it colliding with itself?
public Transform playerPos;
public SpriteRenderer SpriteRenderer;
public float maxShootDistance;
public KeyCode specifiedKey;
public int gunDamage;
public AudioSource shotAudio;
public AudioClip shotClip;
public ParticleSystem bulletParticle;
public ParticleSystem shotParticle;
private void OnParticleCollision(GameObject other)
{
Debug.Log("Collsion with bullet" + " NAME:" + other.name + " TYPE: " + other.GetType());
if (other.gameObject.GetComponent<AINavigation>())
{
AINavigation aiNav = other.gameObject.GetComponent<AINavigation>();
Debug.Log("Shooting Ai");
aiNav.Health -= gunDamage;
}
}
When OnParticleCollision is invoked from a script attached to a GameObject with a Collider, the GameObject parameter represents the ParticleSystem.
Fixed the issue, thanks i appreciate the help man.
Particles cannot be GameObjects
so the particle is certainly not colliding with itself
it might be colliding with the object that the particle system is attached to, sure.
Visual studio is not showing me options for stuff that is UI releated
!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
• :question: Other/None
thx
im getting this sort of weird thing where when i hover over an interactable item the first time, the camera sort of snaps away. it doesnt do it any time after that. it just does it the first time, which is odd.
https://hastebin.com/share/dinivimagu.csharp
its so slight but it keeps bothering me
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i know this is the script causing it because i threw out every other script that i couldnt use at this exact moment
only the itemcontroller, which holds each item's data as a scriptable object, the player movement, the player camera, and the player interact script is active
i dont see anything on my script that would be causing this, since nothing should be affecting the camera rotation
there is nothing in the code you've shown that would affect the movement or rotation of any object. maybe check on the interactPrompt object to see if it does anything in its OnEnable or OnDisable that may affect anything like that
currently its just an image with a text object as a child. i really dont know whats causing it.
it only happens once, when i move the camera onto the object. oddly, if i move the player (and not the camera with the mouse), it does not do the slight jump
whats bugging me is that it wasnt doing this earlier at all
ill try removing parts of code until i see what part causes the jump
Guys what can be causing this?
its super inconsistent which is whats leaving me so confused
Tree also has Interpolation and continious
you should consider showing relevant code considering this is a code channel. if there is no relevant code, then you should consider asking in #⚛️┃physics
oh yeah wait
public float multiplier;
private void OnTriggerStay2D(Collider2D collision)
{
if(collision.transform.tag != "RightHand")
{
Vector2 diff = collision.transform.position - gameObject.transform.position; //character position - transform.position //tree position
collision.attachedRigidbody.AddForce(diff.normalized * multiplier, ForceMode2D.Force);
}
//Debug.Log("push out");
}```
This is the code of uh pushing out player if touching the resource
Could this cause the problem with physics of those items?
what object is that code attached to?
Trees and stones, resources
It's called Smoothness Behaviour, You can see it here
Items only has collider and rigidbody
or could it be because of mass:
oh yes it was problem of mass I changed it to 0.1 and it works better now.
so the tree adds force to the stone, and it adds a lot since it appears to be adding 260 units of force, in the opposite direction
problem was that Since item's mass was small that force was too large so it got thrown out
Player's mass is normal so it pushes out player normally, however throws stuff which has too little mass.
Anyways, thanks!
you should also consider using reasonable amounts of force. 260 is quite a lot
It's reasonable
it's not
It's the kind of physics I want, its for uh squishiness effect.
I'll show you difference.
are you sure you want to be adding 260 units of force using ForceMode.Force rather than something actually reasonable using ForceMode.Impulse?
i'm betting that the reason it seems reasonable is because it is only able to apply that force for a single physics frame before the object is no longer overlapping or its velocity is overwritten
yeah so this is definitely the case
yeah well
either that or your objects are absolutely unreasonably gigantic
i dont know how
i dont know why
but this is the cause
i dont get it though its just an image ;-;
well it has a TMPro thing on it
and this is the inspector for it
and this is the inspector for the text game object 
its just the default things set 😭
Hi all,
Please forgive the potentially silly/simple question.
I have this code.....
https://hastebin.com/share/powanifofe.csharp
Idea being that it deals with the player stats.
I was just wondering if there was a way to write a single method that would update only the specific 'stat' value that's been passed to it?
(as I was typing I thought maybe 2 arrays or lists, one for floats and one for the images and just reference the Index of each? As long as the entries have matching indeces it should work okay?)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the easy way would be just pass a string or something and based of the string update a certain value, but im pretty sure this isnt the best way
I've gone for this route for the moment. I'm sure there's a better way, but this will do for now.
[Header("Player Stat UI Settings")]
[SerializeField] Image[] statIndicators;
[Header("Player Stat Value Settings")]
[SerializeField] float[] statValues;
private void Start()
{
for (int i = 0; i < statIndicators.Length; i++)
{
statValues[i] = Random.Range(0f,100f);
statIndicators[i].fillAmount = statValues[i]/100f;
}
}
void UpdateStats(int statIndex, float statAdjustment)
{
statValues[statIndex] -= statAdjustment;
statIndicators[statIndex].fillAmount = statAdjustment / 100f;
}
you could probably create an enum for that instead of the index, and then either use a Dictionary with this enum as key, or create a new class wrapping the key with the value or image
I'll be honest, that seems massively overcomplicated for what it needs to do.
enum Stat {
Health, Food, Water, Power, Oxygen
}
[Serializable]
public class StatValue {
public Stat Id;
public float Value;
}
// your class
[Header("Player Stat Value Settings")]
[SerializeField] StatValue [] statValues;
well, that's up to you to decide 😄
but it's pretty standard stuff, I wouldn't call it overcomplicating
Oh yeah I'll look at it more later, but for now this works so it's all good. Thank you though, I do appreciate the input. 🙂
How do you call those things between brackets, like [SerializeValue]?
Attributes?
Oh that's just it lol
im building a mobile android game and when the player touches the screen to jump there is a delay, this doesnt happen in unity but only when i export it to mobile, it happens on about 3 phones ive tried some old and some new so i dont think its a spec problem, i do have alot of instantiate and destroy but it still delays before the game even gets there, any way i can lower the delay?
you can do a coroutine which returns null
and then add debugs to see where it delays
then you might improve the method itself
Use the profiler
but i cant
on the pc it runs smoothly
the problem is after im building into mobile
does it matter if i used get mouse click instead of get touch?
You can attach the profiler to your device
after building or using the unity remote thing?
after build
alr ill look into it thanks
Hi I am following this tutorial https://www.youtube.com/watch?v=JFtfyw5u6ro and I am halfway, but suddenly I got these errors and I have no idea how to fix them. I know what the error implies, but it is not the case in this code and it wasn't a problem before. These are the three codes that Ive been using with this tutorial ( i havent changed any other code ) https://hastebin.com/share/zunehidazo.csharp (gamecontroller) https://hastebin.com/share/iroleribor.csharp (spriteswitcher) and https://hastebin.com/share/porakagepo.csharp (spritecontroller) ( i put them in 3 different files to keep it from being confusing) thanks in advance
In this video you will learn how to create and animate sprites in visual novel style using Unity!
Discord server: https://discord.gg/gRMkcyNhwa
Previous part: https://youtu.be/YHwM7d20Gqo
Google drive project: https://bit.ly/3J33zQ4 - for educational purposes only
Music credits:
Chillpeach - Purple
Chillpeach - Vanilla Candy
Chillpeach - ...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
try implementing Object Pooling, if your destroying and instantiating a lot of the same objects.
it's quite simple to implement.
https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html
but without knowing more about your project use the profiler as previously suggested.
about object pooling, you think it could cause only the touch to get laggy but the rest of the objects in the scene run smoothly?
i'm not sure about the touch, but it will definately help you with the scene massively.
The error is saying, that you trying to create another method with the same parameter as there is already. If you are sure, there is no method doubled, try restarting Unity first. maybe delete library folder
im a begginer too so im not really sure but errors get weird when you have an extra bracket or one missing, maybe check that or the indentation
So the 3 codes I've been working in, do not have anything identical. Another script did, but I never opened that one or changed anything in it, so it would be weird for it to be that one
Okay thanks ill look at that
What does error mean?
I have tried closing and re opening unity, but it still gives me the same errors sadly
im 🤏 this close to just destroying the entire project
im not the best with coding but change the names of those two variables and their references
https://hastebin.com/share/itekuqahap.csharp this is a long shot but you could try replacing the gamecontroller script with this, its the same except i tried to fix some indentations im just not sure if those are actually doing anything
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
which ones?
Okay let me try that thank youu
i think what its saying is that you have something called GameController and SpriteSwitcher as variables, but unity may already have a class with those names
The errors are still the same 😞
that or you have duplicate scripts
Ohh, but what do I need to get rid of then?
Let me check that
You have duplicate scripts
find the copy
Destroy the fake
Omg youre right i do have duplicate scripts, i have no idea how that happened
definitely do that
yall are life savers!!!!!!!
now its time for me to have a meltdown over an extremely minor bug
WHY DO YOU HAT EME
WHAT HAVE I DONE TO YOU
im getting bullied by a bool this is silly
I wish I could help, but i know less than you. Have you tried asking chatgpt?
so delete it
find another way to do or smt
honestly i dont even think this is a code issue
at first i thought it was but i think it might just have something to do with the gameobject itself
im starting to wonder if i put the wrong thing in the field
Maybe you could retrace your steps or retry. Its easy to make small mistakes
Maybe you wanna share some useful info about what you are fighting with if its a coding issue
what is the actual issue
thats the original issue i think
yes