#archived-code-general
1 messages · Page 289 of 1
yes thankyou
it still didn't change anything
i think i am having problem with the animation
this is just debugging code to make sure you're triggering your logic. I'd ignore the animation for now and figure out what your position isn't being updated when you're coming into contact with a checkpoint.
guys how can ı transform player on world transform axes
player.transform
Translate takes a last parameter for the coordinate space. Check the docs
yes
thıs ıs for playıng turnıng Z axıs on mouse transform
oh, that was an orange underline, not a red one
what means last paramater dıdnt undurstand my englısh bad lıttle bıt
ye ye
ı am usıng rıder ıde
If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.
now ı can use local and worldspace for transform.translate method?
how can ı change ıt
did you read the page you were linked to?
it explicitly tells you how to switch between world space and the transform's own space
thankyou for heping me means a lot
my englısh not enought ı thınk :/ dıdnt undurstand
Space.Self uses the transform's directions.
Space.World uses the world's directions.
hey there, I've been trying to make this simple function work for like the last hour, and i cant seem to be able to do that. From what i undestand it should cast a sphere from y = 0.5 downwards, and if it collides with something, it should be registered in the rayHit variable. Do i need to add some component to each of the objects before they can be collided with?
Hi. I'm trying to implement explosions with wall collisions. the 2nd function works but now it won't hit the enemy even when there's nothing blocking it. the plan is to have a explosion effect everyone away from cover.
https://pastebin.com/xgLxw5S8
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
any ideas?
Destroy is not instant.
It will happen sometime at the end of the frame.
If you want to destroy every single thing in the way of the spherecast, use SphereCastAll
It will gives you an array of colliders to iterate over.
well this all happens in the Start() method of the script
Also, SphereCast ignores anything that's overlapping the sphere at the start.
oh.
You can combine it with an OverlapSphere to cover your bases
It looks to me like this would cause an infinite loop
since you'd keep hitting the same collider over and over
also, if Physics.SphereCast returns true, then rayHit.collider is guaranteed to be non-null
oh yeah it is an infinite loop apparently
where should ı wrıte thıs
look at the example on that page
it shows you exactly how to move in world space
owww ı see I wıll try now
hi @heady iris since your offering the same solution to Aeronark what about when the sphere cast needs to reconise a wall in the way?
Make sure you aren't getting any errors in the console. I'd also suggest logging what the ray actually hit if Physics.Raycast returns true
so, include the out RaycastHit argument and then log its collider property in an else block (which will run if the raycast succeeds)
yep, it works now, thank you very much
public void CorrectColliders()
{
foreach(Collider2D col in colliders)
{
HeightCollider colHeight = col.GetComponent<HeightCollider>();
colHeight.dynamicColliderHeightLevel = colHeight.startingColliderHeightLevel + (int)entityHeight;
colHeight.ChangeHeightLevel();
}
}
public void CorrectColliderList()
{
foreach(Collider2D col in colliders)
{
HeightColliderList colHeightList = col.GetComponent<HeightColliderList>();
for(int i = 0; i < colHeightList.dynamicColliderHeightLevels.Count; i++)
{
colHeightList.dynamicColliderHeightLevels[i] = colHeightList.startingColliderHeightLevels[i] + (int)entityHeight;
}
colHeightList.ChangeHeightLevels();
}
}
I have these two functions, one of them works fine but the other which is basically just copying the other but for a list doesn't, can anyone help me? Tese functions are part of like 8 separate scripts that are intertwined with eachother so you might have to look at them to figure out what's wrong
colHeightList.startingColliderHeightLevels[i] + (int)entityHeight; this line seems to be the problem, it just isn't outputting the right numbers
//rb.velocity = Vector2.up * jumpSpeed;
``` Guys how to make my jump be better? i dont want to add pressure for the jump
"be better" is very vague
what does "not working" mean, and which one is not working properly?
I see a major distinction between the two methods
One sets a bunch of values and then calls ChangeHeightLevels
The other sets values one at a time and calls ChangeHeightLevel immediately on each
the CorrectColliderList one isn't working, and by not working i mean it's not outputting the right values in this colHeightList.dynamicColliderHeightLevels[i] = colHeightList.startingColliderHeightLevels[i] + (int)entityHeight;
If there's any dependency between these colliders, then they'll behave differently
do you want something more like a jetpack, where you gradually gain speed?
I want 2d platformer jump
I added a else block and it seams like the raycast doesn't recognize the enemy but only the player once they step out of the wall.
if so, call rb.AddForce in FixedUpdate for as long as you want the player to rise up
Log what the raycast is hitting.
For example hollow knight jump its a pressure jump with same velocity by time?
i guess ill call the changehieght levels thing in the for loop but i don't think that will change anything
nope
Hello, i have some kind of flicker in this game object when i'm holding this gameObject, can i get some help here, please
Fen maybe i can add like time to be on max highet before fall?
also it's meant to be called at the end because it's meant to be a single entity for each one if you get what i mean
If you want a consistent velocity until you release the jump key, then just set your vertical every frame.
You'll probably want to do this
Vector2 velocity = rb.velocity;
velocity.y = jumpSpeed;
rb.velocity = velocity;
and it goes up till i release?
But i mean if i want the player will always jump to same max height and i want to make the jump and fall smoother what can i add?
like cooldown between the jump and fall so he stay at air for a bit?
The player will rise up at a constant velocity if you do this.
I don't know what "smoother" means here. If you want weaker gravity, reduce the strength of gravity. If you want to gradually accelerate the player instead of instantly setting the player's speed, use rb.AddForce or use Mathf.Lerp to move your y-velocity towards a target.
Some do, I guess.
how i can do that
by timing how long you've been in the air and reducing gravity's strength until enough time passes, I guess
you need to try out ideas yourself
maybe use an animation curve to change the velocity as you're jumping
i cant its build asset
Like if im on max height reduce the graivty like with lerp to 0 wait a bit and from 0 to the inital one?
That could be interacting with the pixelization effect to cause the weird pattern
The distance is a void Update of the camera + 4F toward
and is being updated
to clarify: it's not a "void update". You're setting the object's position in the Update method.
Prob
4 meters is pretty far away.
I see that the object has a rigidbody, though, and that you're setting transform.position
You've also turned on all of the "freeze" constraints
I suspect these are playing poorly together. Setting the transform's position skips the physics system entirely.
Try setting rb.position instead.
oh ok, let me try
do that for the overlapshpere before the foreach loop?
No. I'm asking you to check what the raycast is hitting.
I'm not asking you to log what the OverlapSphere call is finding. Your code already does that
for each thing you hit, it logs whether or not the raycast hit anything
But you aren't logging what the raycast is hitting
Do that.
You'll need to add an out RaycastHit hitInfo argument to actually capture that
(this argument goes between the direction and the max distance)
Physics.Raycast(start, direction, out RaycastHit hitInfo, maxDistance, layerMask)
Like this?
Your hit info , should contain the information on the object your raycast hit
@heady iris
No, because you're trying to use hitInfo when Physics.Raycast returns false
that means it didn't hit anything
you need to log it in the else block.
Yeah remove the !
switch the logic around and the debug log can only tell racast hit
You are still trying to use hitInfowhen the raycast does not hit anything
I feel like you aren't understanding the point of hitInfo here...
when the raycast hits a collider, hitInfo is populated with information about the hit
We want to find out what collider the raycast is hitting when the enemy fails to take damage.
I'm not even sure how to implament that casue I got the code from a tutorial that was set to on click instead of exploding over time https://www.youtube.com/watch?v=ZoyFL8tH0SU
Explosions are a powerful and fun effect to add into your game. In this tutorial we'll add point-and-click explosions to both apply damage, and knock back Rigidbodies in a scene. We'll also implement relatively simple method o determining if a wall is in the way of the explosion. If there is some obstruction, then we'll say the explosion won't a...
I tried to modify it to suit a projectile rather then a click but I have not been able to translate it into a projectile
Implement what?
I am literally just asking you to add Debug.Log(hitInfo.collider); to the branch that runs when the raycast hits something
Imlament hitinfo
oh
just bringing this up again because i can't for the life of me figure out what's wrong
added that into the log and it's not even working
yes, because you're filtering the log
you're only viewing log items that include the word "Blocked"
this is absolutely going to depend on the rest of your code
HeightCollider and HeightColliderList are two completely separate types
@heady iris because i marked blocked in the debug log. I have no idea how to implament this and it's causing me a headache trying to find out. I know that the bomb only responds to the player's collision not the enemies
You are still trying to acccess hitInfo.collider when the raycast does not hit anything
Now it's causing errors, because hitInfo.gameObject is null when the raycast misses
Please read what I'm writing.
you added that code to the branch that does not run when the raycast hits something
The else branch runs when the raycast doesn't hit something.
if (Physics.Raycast(...)) {
// hit
} else {
// miss
}
You are, however, also correctly logging when you do hit something, so that's good.
This means that your raycast smacked into an object named Plane.
to get a little more information out, you can include a "context" object in that log
Debug.Log("Blocked", hitInfo.collider);
When you click on this log entry, the hierarchy will highlight the object with the collider on it.
I'm guessing that your raycast is starting from inside or under the floor and is hitting it
You can verify this by adding a Debug.DrawLine
Debug.DrawLine(transform.position, hitInfo.point, Color.red, 1f);
their code is effectively the same
i can post all the scripts that i think are relevant
This will draw a red line from the source to the hit point. The line will last for one second.
a powerful website for storing and sharing text and code snippets. completely free and open source.
tbh I don't think any other script is needed as the problem stems from the value being wrong, and it's not like anything changes the value apart from the script that i showed
I added thoes in, here's what i got
you're doing quite a bit of strange list manipulation in your HeightCollidersList class
I assume you think setting one list to another copies the contents of it?
yeah
it does not!
i made this script myself so it probably has lots of problems
currentColliderHeightLevels references the same list as dynamicColliderHeightLevels now
if you want one list to be an exact copy of another list, use Clear() and then AddRange()
how would i do that in the context of my code
@heady iris
by calling currentColliderHeightLevels.Clear() and then calling currentColliderHeightLevels.AddRange(dynamiccolliderHeightLevels);
you'll need to zoom in to see the red lines; I can't see anything in the video
a red line should appear each time that "Blocked" is logged
ok ty
is there a solution here?
wow that was it lmao, i was going crazy for so long tysm for this, i just need more knowledge of c# even though i've been using it for so long
Assigning a variable does not make a copy of the referenced object.
That line is shooting way into the floor
I wonder if your enemy has a collider that sticks out somewhere weird.
it's the ground plane
Yeah, but if the ray was being fired at the enemy, shouldn't it be pointing towards the enemy?
it shouldn't nosedive into the floor
Use this technique to log each collider that is hit by the OverlapSphere. Check out where that collider actually is.
it's nose diving at the floor becasue it reconises the floors and anything it doesn't reconise hitsd
so, you'll log
if the problem is that the OverlapSphere is finding the floor, you should use layer masks to avoid including the floor
THATS NOT THE PROBLEM
I don't understand what you mean by this, then. The code fires a ray at the position of each collider that the OverlapSphere hits.
If a ray is shot into the floor like that, then there must have been something under the floor that the OverlapSphere detected.
@heady iris look at the tutorial. I copied and pasted thier code into mine.
Yes. I just described what your code does. The code also sounds very reasonable to me.
I'd suggest using Debug.DrawLine right before the raycast to show where the target point is
Debug.DrawRay(transform.position, Hits[i].transform.position, Color.green, 1f);
This will draw a longer green line between the bomb and the thing it's trying to hit
I'm sorry I don't need to debug.log my way through everything when the problem is either the bomb doesn't do anything or it explodes everything no matter what wall is the way
if there is better code to add collision to explosions please let me know.
what timestamp in this video demonstrates the problem? to me, it looks like every single bomb that went off without a wall in the way reduced your health, and that every other bomb didn't hurt you
oh, is that a healthbar above the enemy's head?
yes
yes
so this is not the case: the bomb is hitting some things and missing other things. It's not an all-or-nothing problem.
yes
that was the only time I got the bomb to work
every other time the bomb has to go through every wall to work
that is the point of this code now is to add collision to the explosion
so, do this to visualize the rays you're firing (the full ray, not just the line from the source to the actual hit point)
It's possible that your rays are being fired from very close to the ground, making it a bit random as to whether the ground plane blocks them.
I did that and it's not telling me what I already know from previous code
You only draw a ray if you don't hit anything.
That's why this would be a second Debug.DrawLine call.
done unconditionally before you perform the raycast at all
the theory here is that your raycast is being fired into the ground, this causing the "Blocked Plane" message to appear.
This will show you the attempted raycast. It should draw a line between the bomb and each thing that can be blown up.
If that line winds up under the floor (or is flush with the floor), that's a problem.
Blocked plane shows because it's the name of the gameobject thats part of the ground
Yes.
and it's not reasonable for the floor to be preventing the bomb from hurting the enemy in that video, right?
no it's not because it's using a Physics.OverlapSphereNonAlloc
that has nothing to do with blocking the damage.
damage is blocked if a raycast between the bomb and the target hits an obstacle.
the OverlapSphere has nothing to do with blocking damage. It just finds things that might get damaged.
that's why I'm asking you to add Debug.DrawRay(transform.position, Hits[i].transform.position, Color.green, 1f); before you do the raycast
If the raycast is wrong, then damage might get blocked by something that makes no sense as a blocker
it might be what layers I set the layer mask with
please do this and verify that the line that's drawn makes sense
you should see green lines between the bomb and the damageable object
I added the lines and the red lines don't even go for the enemy
Are you only drawing the line if the raycast doesn't hit anything? I expected to see overlapping red and green lines.
thıs cods got any mıstake or?
not so far no, thats why Im sending you the step-by-step debugging physics messages
It's drawing lines to things it hits too. look at the console
Show me your new code.
also, it looks like you got rid of hitInfo, which makes this harder to debug again
I asked you to draw the green line before the raycast, so that you unconditionally draw the green line.
The point is to see the attempted raycast along with the line between the source and the point we hit
ı dıd my englısh so bad and dıdnt undurstand much but thank you
it is before all of that logic
well the first step is adding the debugs to see if method even runs, start with that
It is not. You draw the green line in the else branch.
That code only runs if the raycast misses.
Draw the line before you do the raycast.
If you don't understand why this matters, you need to stop what you're doing and follow some of the pathways on !learn -- this is really fundamental stuff here.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if the Log is not printing inside , then you click here and follow the rest of steps @torpid depot
okay lookıng
look man I'm just making a demo build and optimisation is not my problem. it's just explosions with collisions and clearly the code i got is a lost cause and I am will to rewrite the entire thing for a better result please
This isn't optimization. This is literally what the code does and does not do.
I asked you to draw the green line before doing the raycast. You didn't do that. You drew it after doing the raycast, and only if the raycast missed.
That's completely different.
Debug.Log("Hi");
if (foo) {
//
} else {
//
}
versus
if (foo) {
//
} else {
Debug.Log("Hi");
}
then let's rewrite the entire thing cause there saving this code fuction
the entire point why I build the code that way was because the tutorial said to do that to detect walls.
se
@rigid island only thıng ı undurstand from there is Some settıngs can connect collıders for a whıle rıght?
Yes, and all of the logic in the code is fine. It makes perfect sense to me.
I think there's a problem with where the bomb or colliders are positioned.
when it's not doing anything it's clearly a lost cause
no... the first to check is the log. Did you check the log?
It's not doing anything because you've literally ignored my suggestions and implemented something else.
I can't help you if you just do your own thing.
you removed the hitInfo debugging and you're insisting on drawing that green line in the wrong place. I don't know what else to tell you.
fine then just show me better code to use
ı dıd clıck for 2D one and look at some lınks
but not undurstand
my guy, you're not following what I'm saying clearly.
cause your solutions won't work unless i restructure the code from scratch
Did you put a Debug.Log first ? @torpid depot
I am literally asking you to add one line of code in the correct place.
okay ı am doıng that one sec
You've spent 30 minutes not doing that.
ok, make sure its NOT inside the if statement of tag, just in OnCollisionEnter
Debug.DrawRay(transform.position, Hits[i].transform.position, Color.green, 1f);
This belongs before the raycast happens.
before this line happens?
Yes.
only workıng when player touch ıt
bullets not workıng
what is this video supposed to show
also why does the script you sent different than before ?
You showed me you put the log inside somewhere, but never showed the console window
when player touch enemy ıt works but when bullet Not workıng
what works?
debug log example ıs workıng when enemy touch player
@heady iris well here it is
but when bullets touchıng enemy not workıng
but why are you showing me log inside enemy and not bullet?
show how you setup your bullet
inspector + script
Ah, my bad: use DrawLine, not DrawRay. I must have made a typo.
DrawRay is more like what Raycast takes
a position and an amount of offset for the end point
Also, make the scene view larger to make it easier to see what's going on, and consider making the bombs have huge range, too
so that they always try to hurt both you and the enemy
that'll make things more consistent
so the bullet is not a trigger collider without rigidbody, how do you expect OnTrigger to work ?
should also not move with Translate, use a rigidbody and put velocity
It works on enemy because one of them has a rigidbody + trigger
corrected
It looks like the raycast is immediately hitting the floor. Notice how there's no red line going towards the enemy at all, even though the bomb was blocked.
that means that the red line is extremely short
ı have to use rıgıdbody?
Try adding a small vertical offset to both the bomb's position and the target's position.
If your object is moving you should be using a rigidbody , yes.
transform.position + Vector3.up * 0.1f
``` basically
ı wıll make kınematıc rıght? Rıgıdbody
why would you kinematic?
thats not how that works
you should learn more on kinematic, its better suited for it not moving
You need Gravity scale to 0
Is the use of static events in Unity considered a best practice?
or the enemy transform is on their feet so the raycast is shooting thier feet. the cosole saids it's hitting them in the trasform pivot
not really
Right. That's why the raycast is instantly hitting the ground
it's a practice. it's hard to say that it's "good" or "bad".
I don't use many of my own static events, but I do use lots of events on singletons.
they're valid in some occasions but not "the best" all the time
Adding a small vertical offset will fix that, if that's the problem.
yet the it's reconsises the player object and is able to damage them
global events like public static event Action OnGameOver is pretty valid
It uses the transform of the collider. If the player has a collider parented to them, then perhaps that collider is floating a bit
so rigidbody wıll be dynamic and 0 gravıty scale right?
thıs ıs best for optımıze?
mate at this stage you should not worry about any optimization
yes the player in general is floating
ow okay
yes just get stuff working
That'll do it, then.
Debugging with DrawLine can help you to spot these kinds of issues.
I use it a lot when doing anything involving raycasts or picking destinations
thank u my man <3
np. Did you get it working ?
tryıng now fırst eatıng my dınner ı am so hungry xdd
it really depends on how complicated your game is, in a larger game you might end up wanting to cut down on global variables to make debugging easier, but for a smaller game you probably won't care about that
What alternatives are there to static events? Can either manage the registration/deregistration manually, through static or some singleton... and what else?
the alternative is..non-static events!
either through a singleton, as you mentioned
or through something that gives you the correct reference
ok. make sure you also change the movement from Translate to rb.velocity
for example, imagine a game that has a turn based combat system
You might start by creating a static event for "Next Turn"
but then, later, you decide you want to have multiple battles happening simultaneously
a static event no longer makes any sense
so you instead give everyone a reference to a BattleManager that has non-static events on it
In that situation, using a singleton instead of static events makes the transition a bit easier.
tried moving the collision upward and i seriously doubt that's what causing it
but that was transform
what ıs dıfferent wıth that
Add a small vertical offset to the bomb's position and the target's position in your code
moving a transform directly is the same as teleporting, it will not respect the physics simulation accurately, it will be janky.
Rigidbody moves the transform after it has simulated the physics
so more healthy for colliders or somethıng rıght?
because ıt can transform under the collıder somethımes maybe
but when physıcs sımulatıon happens thıs wıll not
I switched the game logic and now the enemy is taking damge while the player is uneffected
colliders are part of physics sure, but anything that should be moving Is better for Rigidbody because of Physics.
I really doubt this is a collision issue
okay got ıt
this proves that it's a collision issue. You switched it so that the target takes damage when the bomb is blocked
Of course things are reversed now. You reversed the logic.
I can't help you if you completely ignore my advice and do other random things.
@heady iris What about setting up just 1 singleton to manage registration for all events across a game? Or would that just be a bit too coupled and a bit of a mess at some point.
I'm saying this is a layer mask issue. I don't think it has anything to do with collision
All I am saying is copy and paste my code into your own project and see what happens
https://pastebin.com/xgLxw5S8
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this code does not match the code you just screenshotted.
Please just do what I suggested. I am very confident that it will fix your problem.
Add a small vertical offset to the position of the bomb and the position of the target when you do the raycast.
fine, I can make a new paste. and i did exactly what you suggested
Don't completely reverse the logic of your code.
that's only way i can debug it in a meaningful way
if you have no idea what any of this means, you shouldn't be asking people to spend an hour of their time to debug it while constantly refusing to actually follow instructions
Assuming that the singleton really is single -- i.e., you don't later realize there should be multiple instances -- then that's reasonable.
for example, I have an EncounterManager that deals with events like "start encounter" and "end encounter" in a single game session
I also have a GameController that lives for the entire duration of the game and handles stuff like switching scenes
After loading a game scene, it tells the EncounterManager that it's time to start a game session
That makes sense
I was trying to avoid singleton's.. but it seems difficult to do so
I have followed your instructions the entire time and it hasn't resolved anything. I tried all of these solutions for weeks and it still hasn't resolved anything. thank you so much for helping me but I'm better off redoing the code from scratch
This is patently false. You randomly reversed how your code works #archived-code-general message
...instead of just adding a vertical offset, like I've told you to do several times now.
I am quite confident that your problem with the raycast hitting the floor will be resolved by making it not hit the floor.
If I sound frustrated right now it's because I am.
If you don't know how to do something, ask me instead of just trying other random stuff
i switched for a moment to debug the game. I then switched it back once It told me what the problem is.
walls.value is a layer mask and it's their to reconise the ground so that it would not happen and I specifically added ! make sure anything that is not in that layer mask.
i'm calling it a day and move one
is there a camera compositor for the standard render pipeline? i want to have my fps viewmodel on a seperate camera with a seperate FOV to my main camera
Hey guys, I need help in finding a logic to coding a simulation.
I have extracted data from F1 for a particular race.
I have the X and Y coordinate. I also have the speed at each point.
Now all I need to do is write a code to make the prefab move from point to next with the speed given in the data.
I tried everything but for some reason the speed in the Unity is not matching with real world.
I used chatGPT help as well but it doesn’t work.
I used speed multiplier but then how do I know how the value? It’s really hard with trial and error.
I think I am missing something and hope that you guys can help me.
I don’t need a script, if anyone can tell the steps to follow that enough.
Show how you move the objects. Probably need to multiply by Time.deltaTime
It's unclear what data you actually have here. You have "speed at each point"?
What about position? What about race clock? You wouldn't need the speed at all if you have the positions at various times.
This is how my code looks like
doesn't show how you call it. Is it in Update()?
Plese tell me more, I have race time. How I can use that logically to make the prefab move? The Race time is not at equal intervals.
You can see the data here: https://docs.google.com/spreadsheets/d/1HrrtCXIPnyceK-Eml1eQ5jshSQldjxNt6YqXtd8tpQw/edit?usp=sharing
Worksheet
Date,SessionTime,DriverAhead,DistanceToDriverAhead,Time,RPM,Speed,nGear,Throttle,Brake,DRS,Source,Distance,RelativeDistance,Status,X,Y,Z
2021-06-19 13:03:06.950,0 days 00:17:39.747000,383.9683333,0 days 00:00:00,6795,60,1,16,False,8,interpolation,0.04846581397,0.0000005288105236,OnTrac...
Yess, It's in Update
Looks like Time and Distance are the two important pieces of information here
Distance presumably is distance along the track
That's essentially the current position along the track
You would just interpolate between the current and previous position at the current time
You probably want a spline of the whole course in order to properly interpolate along it.
You mean the time interval for the interpolation should be the difference between the times at two points right?
Yes
I think your lerping is causing a problem. Maybe something like this would be better:
private IEnumerator AnimateCar(Vector3 startPos, Vector3 targetPos, float duration)
{
float timer = 0;
while (timer < duration)
{
timer += Time.deltaTime;
transform.position = Vector3.Lerp(startPos, targetPos, timer / duration;
yield return null;
}
//Start Coroutine again with next values
}```
Alright, thank you. I'll try this method and let you guys know how it went.
@somber tapir thank you for the code 🙂 Yes, I did try the Coroutine methods as well. Sadly it did not work.
But after the above discussion, I think I realized what I did wrong.
I was not using the time data directly, I was focusing on speed and distance and then calculating the time.
I have a feeling, in your code, if I pass the duration as the difference between the times at two points then it will work.
Thanks a lot for the quick reply guys! you are amazing! Thanks 😄
How would I go about trying to lerp my camera's fov as a callback? For context, I'm triggering off a button press from input actions and I'm trying to figure out a way for the camera fov to lerp from 60 to 40 over a period of time, but I'm not sure how to do that outside of the update/fixedupdate functions
So every path with "dddwetgergtrt" is apparently illegal, somehow? dddwetgergtrt is "Untitled (143).level"
cs if (!File.Exists(Path.Combine(openedCampaignFolder, dddwetgergtrt))) { File.Copy(Path.Combine(Application.persistentDataPath, "Levels", dddwetgergtrt), Path.Combine(openedCampaignFolder, dddwetgergtrt)); //C:\Users\itsbl\AppData\Local\Temp\w8k55zzl.702\Untitled (143).level }
How do you know it's "illegal"?
If there are errors, you should psot them with the original question
the variable name has nothing to do with the problem
i mean, that's pretty much it:
ArgumentException: Illegal characters in path.
Try without the space
yeah, I said in the post that the variable is "Untitled (143).level" which is apparently illegal
are you sure that part is the illegal part, and not perhaps the wait no, that's probably fine. in the folder name?
Your resulting path has invalid characters. You can call Path.GetInvalidPathChars() and look at the contents of the resulting array to see the invalid path characters on your current platform
Do note that this is platform-dependent, and what's illegal on Windows might not be on Mac or Linux
yeah, it's a windows generated temp folder anyway
I have to wonder if there's a weird invisible character on the end of the file name.
ah yeah good point, could be that pesky character that plagues input fields
looks like it's the whitespace
wait.. it might actually be a newline
it was a newline
AHHJASKJHLADSHKGASDFKLHJ
SO MUCH TIME WASTED 😭
anyways thanks fellas
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI; // Include this if you want to display FPS on a UI Text element.
public class ScreenCaptureToTexture : MonoBehaviour
{
[DllImport("CaptureFullScreen")]
private static extern IntPtr CaptureScreen(ref int width, ref int height, ref int bytesPerPixel);
[DllImport("CaptureFullScreen")]
private static extern void FreeMemory(IntPtr buffer);
private Texture2D texture;
private MeshRenderer meshRenderer;
private int frameCount = 0;
private float timeElapsed = 0.0f;
private float fps = 0.0f;
public Text fpsDisplayText;
void Start()
{
meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer == null)
{
Debug.LogError("MeshRenderer component not found.");
enabled = false;
return;
}
}
void Update()
{
int width = 0, height = 0, bytesPerPixel = 0;
IntPtr buffer = CaptureScreen(ref width, ref height, ref bytesPerPixel);
if (texture == null || texture.width != width || texture.height != height)
{
texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
}
texture.LoadRawTextureData(buffer, width * height * bytesPerPixel);
texture.Apply();
meshRenderer.material.mainTexture = texture;
FreeMemory(buffer);
// Update FPS every second
frameCount++;
timeElapsed += Time.deltaTime;
if (timeElapsed > 1.0f)
{
fps = frameCount / timeElapsed;
frameCount = 0;
timeElapsed = 0.0f;
// Display FPS
if (fpsDisplayText != null)
{
fpsDisplayText.text = $"FPS: {fps}";
}
else
{
Debug.Log($"FPS: {fps}");
}
}
}
}
How can i make this async / better as currently it drains 60 FPS when active
is there any way to get rid of this gap between the ground that circle colliders have? My player is using a 1x1 one and it isn't able to go into a one tile gap because of this
Would like to not have to make the collider smaller since I already have all of the sprites based on that size
more zoomed in:
guys ı have a questıon
how can ı take thıs vector3 Blue one
ı want a random transform ınstantıate but only blue side
I would randomly pick left/right and top/bottom
then generate a horizontal and vertical distance
then I'd have four cases, one for each pair of horizontal and vertical side
which would take the corner position and either add or subtract the distances
It's a bit verbose.
Maybe you can do:
int horizDir = Random.value < 0.5f ? -1 : 1;
int vertDir = Random.value < 0.5f ? -1 : 1;
float horizOffset = Random.Range(0f, 10f);
float vertOffset = Random.Range(0f, 10f);
Vector3 result = center;
result.x += horizDir * (width / 2f + horizOffset);
result.y += verTdir * (height / 2f + vertOffset);
navmesh it for a pointcache and sample from that
after that codding ı undurstand my cod experıence not even middle xd
but thank you <3
ı undurstand what you mean here
but ın cod thıs ıs so hard
like ı know u dıd use same thıng if else in just one letter but ı dıdnt learn ıt yet
It's definitely awkward to read
width and height are the size of the inner box
and center is the position at the center
You randomly decide if you're going left or right
Then you add half of the width, plus a random number, to get how far you go
multiply that with horizDir to get either a negative or a positive number
The number will be between width/2 and width/2 + 10f in this example
So it'll move you somewhere into the blue area horizontally
I understand the logic
very logical
But as I said, my coding knowledge is a little insufficient for this
thank you for help <3
I'm trying to render a mesh using compute buffers, without sending data back to the CPU.
When I try to render the mesh, the number of indices is zero and the mesh doesn't render, but I do get draw calls in the render pipeline.
I previously used Ver and Tri compute buffers to render the mesh using the meshRenderer component and it worked fine, so the problem is probably with the shader.
How can I make it work?
draw call :
shader.Dispatch(0, (res + 2) / 32, (res + 2) / 32, 1);
Graphics.DrawProcedural(
material,
new Bounds(transform.position,transform.lossyScale*10),
MeshTopology.Triangles, 6*(res + 1) * (res + 1), 1,
null, property,
UnityEngine.Rendering.ShadowCastingMode.On, true, 0
);
Shader :
Shader"Hidden/VertexColor" {
SubShader{
Tags{ "RenderType"="Opaque"}
Pass{
Cull Off
CGPROGRAM
#include "UnityCG.cginc"
#pragma vertex vert
#pragma fragment frag
StructuredBuffer<int> Tri;
StructuredBuffer<float3> Ver;
StructuredBuffer<float4> Col;
float3 worldPos;
float4 vert(uint vertex_id : SV_VertexID, out int vertexIndex : TEXCOORD0) : POSITION
{
vertexIndex = Tri[vertex_id];
float3 position = Ver[vertexIndex];
return mul(UNITY_MATRIX_VP, float4(position, 1));
}
fixed4 frag(int vertexIndex : TEXCOORD0) : SV_TARGET
{
return Col[vertexIndex];
}
ENDCG
}
}
Fallback"Diffuse"
}
I think you could try asking that on #archived-shaders ? Not very fast response, but probably more knowable people about the topic.
Okay, I'll try there
Ive been working on a little project just for fun and I came across a issue, The sounds play just fine whenever their not set up to swap scenes but whenever they are set up to swap scenes they do not play
ScriptableObject or Sound Definition Dictionary
hey can you guys help me remember the name of that attribute that registers a static method to run while a unity project is loading?
you can specify different stages like before assemblies loaded, before first scene loaded, subsystem registration, etc.
google just says do Awake() but i can't use that in this situation
RuntimeInitializeOnLoad or something?
While typing in an attribute [] the completion list will be restricted to attributes so you can always go through it manually
Well, that doesn't work if you don't remember the name at all, but most of the times it clicks when you see it
I have definitely typed in each letter of the alphabet to look at every suggestion haha
my list was l o n g
Ah yeah in the lastest VS versions the list shows items from all namespaces so it can get quite cluttered, but it can be turned off temporarily by clicking the green "+" icon bottom-left (right?) of the list
That way you only get the stuff from what you have using directives of
can someone explain the different components of this class? I don't understand why it needs to be so complicated for something that seems so simple https://gdl.space/ribizexiye.cs
Whatever this is, it likely doesn't need to be that complicated.
it's pretty
im just so lost trying to create an ability system lol
all the ones ive found on github seem needlessly complex, but maybe im being naive
Hard to say without knowing what AttributeValue is but likely it's a flexible, extensible, and perhaps semi-serializable attribute system
It's probably geared towards easy management in the editor
{
[Serializable]
public struct AttributeValue
{
public AttributeScriptableObject Attribute;
public float BaseValue;
public float CurrentValue;
public AttributeModifier Modifier;
}
[Serializable]
public struct AttributeModifier
{
public float Add;
public float Multiply;
public float Override;
public AttributeModifier Combine(AttributeModifier other)
{
other.Add += Add;
other.Multiply += Multiply;
other.Override = Override;
return other;
}
}
}
just a struct
A serializable struct with a companion serializable modifier
Yeah it's all geared towards designing things in the editor
yeah, most are since they are for public use
It still doesn't need to be that complicated
my stat system is basically a dictionary with key type enum to a list of modifiers
They felt it necessary to create a lookup into their existing structure instead of just creating a dictionary from it, and that introduced the complexity
im just having a hard time wrapping my head around the "steps" in the process since there are so many components: abilities, effects, modifiers, cues, tags, etc
thats what I have right now too, just a dictionary with a stat enum and a class that holds a base value and a current value
tag stuff I use bitmask
what happens when you need more than 32 tags though?
then you do long enum
you get 64 then?
make 2 enum
lol
for 128
ideally you have an enum for fluff (fire, ice, nature), and an enum for stats (speed, damage), then maybe some more fluff tags like weapontypes
no tags as in "Effect.Buff.Stun" or something like that
some bit shifting then decide if this modifier is applicable and stash it into your dictionary
which when an effect tries to get applied, will check required/ignored tags
so say a player has an Invulnerbility tag, any effect which damages the player can only be applied when that tag is removed
that's something you'd check at the time of say dealing a source of damage to the unit
apply source -> conditional checks
most like general character modifiers you can calculate and stash at the time of equipping
yes, i understand the idea, i just can't wrap my head around how to code a system that would let all of those work together
How do i hide the text after i pick it up. I tried a bool but i kept giving me a error. code-```cs
public class ObjectGrabbable : MonoBehaviour
{
private Rigidbody objectRigidBody;
private Transform objectGrabPointTransform;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
private void Awake()
{
objectRigidBody = GetComponent<Rigidbody>();
}
public void Grab(Transform objectGrabPointTransform)
{
this.objectGrabPointTransform = objectGrabPointTransform;
objectRigidBody.useGravity = false;
}
public void Drop()
{
this.objectGrabPointTransform = null;
objectRigidBody.useGravity = true;
}
private void FixedUpdate()
{
if(objectGrabPointTransform != null)
{
transform.position = Vector3.SmoothDamp(transform.position, objectGrabPointTransform.position, ref velocity, smoothTime);
objectRigidBody.MovePosition(transform.position);
}
}
}
looking through all these examples that are geared toward the editor hasn't been helping
i'd go with creating a general system of stats and modifiers that apply on equipping first, then deal with these additional conditions later
i already have
public class PlayerInteractUI : MonoBehaviour
{
[SerializeField] private GameObject containerGameObject;
[SerializeField] private PlayerInteract playerInteract;
[SerializeField] private TextMeshProUGUI interactTextProUGUI;
[SerializeField] private Transform playerCameraTransform;
[SerializeField] private LayerMask pickUpLayerMask;
private void Update()
{
float pickUpDistance = 2f;
if (playerInteract.GetInteractableObject() != null && (Physics.Raycast(playerCameraTransform.position, playerCameraTransform.forward, out RaycastHit raycastHit, pickUpDistance, pickUpLayerMask)))
{
Show(playerInteract.GetInteractableObject());
}
else
{
hide();
}
}
private void Show(IInteractable interactable)
{
containerGameObject.SetActive(true);
interactTextProUGUI.text = interactable.GetInteractText();
}
private void hide()
{
containerGameObject.SetActive(false);
}
}
im specifically trying to create an ability system
that obviously needs to be able to change those stats
well, beyond the stat stuff, anything conditional or more unique to calculations are usually done through a series of lists of polymorphic calls like Use() or Apply()
for what I've seen and done
void TriggerAbilities(TriggerAbilityType triggerType)
{
IEnumerable<TriggerAbility> abilitiesToTrigger = triggerType switch
{
TriggerAbilityType.AbilityOnHit => ability.PrimaryAbilityTriggerDict[TriggerAbilityType.AbilityOnHit],
TriggerAbilityType.AbilityOnCast => ability.PrimaryAbilityTriggerDict[TriggerAbilityType.AbilityOnCast],
TriggerAbilityType.AbilityOnExpiration => ability.PrimaryAbilityTriggerDict[TriggerAbilityType.AbilityOnExpiration],
TriggerAbilityType.AbilityOverTime => ability.PrimaryAbilityTriggerDict[TriggerAbilityType.AbilityOverTime],
_ => Enumerable.Empty<TriggerAbility>()
};
foreach (TriggerAbility triggerAbility in abilitiesToTrigger)
{
triggerAbility.Trigger(transform.position);
}
Stuff like that
add them to your dictionary of modifiers and calculate again
when they expire, use the key to remove it then recalculate it again
would that be performant?
if you calculate only what its being modified, sure
dont need to update all 100 stats if you're only updating speed
how would I differentiate current and max stats in this case? have a seperate modifier list for max and current?
eh, I guess once you're done calculating if it's over the cap then shave some of the stats off
you still would have the same amount of modifiers and you'd just do a full recalc when removing them anyway
well i mean more so like differentiating between a change to max health and current health in which current health shouldn't respond to a change in max health
that's dependent on how you want to do it, but usually games will increase max health and not change current
WoW actually did change current health with max health upgrades which I exploited for a while
Hey, I'm having a very weird problem with my script. It executes the Update function in the editor, outside of play mode. I'm not sure why, but I think it might have something to do with it being a Selectable Class.
but how I implement it will change the behaviour of all of the stats
things like movement speed should change both current and max
all other stats only are below their max in the case of a debuff
what I do, specifically for health, when max health is changed I make my property check if current health it greater than it, and if it is then I shave it down back to the point where max health stands.
I don't have a 'current' health stat that's modifiable by modifiers, but the max health does
so health/mana would be an edge case
edge case in a sense that I don't consider them proper stat,s yeah
at least current levels of them
but that's just my implementation, but you can always make two entries for each stat if you wanted to
i just have my StatValue hold a max and current
im not seeing anything here that would execute out of play mode
I know, which is why I don't understand why it does it. I can't even move my game object because of it. Is this a bug or something?
If I make this a Monobehaviour instead of a Selectable it works just fine
Is there a way to prevent this from happening?
there's always if (!Application.isPlaying) { return; }
that's such weird behaviour for that to work in the editor without specifying execute in editor
the Selectable base class has [ExecuteAlways]
interesting
Remember that the method version of IsPlaying exists so you can correctly support prefab mode during Play mode
In the case of projectiles, how should I deal with the "source" and "target" since when casting the ability, there will be no target until the projectile hits
coroutine to wait until target is not null?
send the source entity with the projectile object
when it hits, unwrap and read the source entity's stats
from what I can see RotateAround should rotate the transform around a point in space, keeping its distance from that point, right?
void Update()
{
_rotateTime += Time.smoothDeltaTime * _rotateSpeed;
transform.RotateAround(_rotatePoint.position, Vector3.up, _rotateTime);
}
Then why does this code result in this? (it's hard to tell, but the gray cube is getting closer and closer to the point its suppose to be orbiting).
Maybe your pivot point isn't where you think it is.
what does accumulation of time represent here? Just speeds it up, right?
I was thinking the pivot is desyncing, but it shouldnt really matter as, so I could only guess too that the pivot is just wrong
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 axis, float angle)
{
Quaternion rotation = Quaternion.AngleAxis(angle, axis);
return rotation * (point - pivot) + pivot;
}
That's my version of rotateAround
That the rotate time is continually increasing might indicate an issue, unless you're sure the rotate speed is low
it could also be a problem of parenting, and just losses in the transform hierarchy
Is sensitivity set to zero in the inspector?
Are there any other components that might be trying to constrain it's change in position?
Obligatory "don't multiply mouse input by deltaTime"
im not sure. I stopped using RotateAround and it works now.
is there a way to find what object is causing this? I have 0 idea what object its talking about. It only happens when I click a button but that button doesn't instantiate anything.
check prefabs
it would say in the inspector if it contianed it right?
like if i click on the prefab file
yea i just checked every prefab in the project nada
has anyone encountered unity editor making local variable null unless observed in the inspector? i am using unity 2021.3.32f1 version
did you tag it with [SerializeField]?
You can't observe a local variable in the inspector...🤔
it was just badly worded ithink
its actually set to public sorry for the confusion
there are limitations on what types can be serialized, you should check the docs
Not quite sure what the problem is. Maybe share more details and code.
well i've had lots of classes but im not sure as what is causing this... basically this script has a public variable and another script accesses that public variable. I tried setting a debug log to show that the variable is there and it has a value but when the other script tries to access it tells me null reference but when i click on the other script it shows the variable on the inspector, and now when that script accesses the variable it now shows the value...
ive tried this multiple times not clicking the script but it only shows not null if script with the variable is shown in the inspector...
Share code and errors.
we're not psychics and can't read people's minds, show code
It kinda sounds like you're misinterpreting the issue.
oh man...
I'm trying to make a grid but when I zoom out some of the lines start to disappear like this, second picture is how its supposed to look like
I already have anti aliasing on so im not sure how to fix it
Hey, how do I enable and disable reflections of a standard material (in code)
I'm not sure if that's your problem but maybe one script is setting the variable in Start and the other one is trying to access it from Awake. Awake is called before start so in most cases you will have a null error. I'm not sure about this, because your question is kind of vague, but this may be the solution
This is a coding channel id:browse
yeah i am asking how to do it in code
yeah this seems more like a texturing thing
alr
https://docs.unity3d.com/ScriptReference/Material.html
maybe you want to use SetFloat to change something like the smoothness or metallic property. If those are set to something non 0 in the first place
Body[PlayerNo].DisableKeyword("_GlossyReflections");
Body[PlayerNo].SetFloat("_GlossyReflections", 0f);
I am doing this but it's only turning the bool off but not really effecting the material
Can you post a screen recording of zooming out? And add some detail with how you're going about generating your grid
It's a really large mesh with a grid texture set on repeat
Are you using point filtering and generating mip maps?
The answer for you likely lies somewhere in these settings
{
public string GUID;
public RarityType rarity;
public int quantity;
public GenericDictionary<ItemStat, float> affixes;
public int itemLevel;
public int sellPrice;
public ItemSaveData(string _GUID, int _quantity, RarityType _rarity, GenericDictionary<ItemStat, float> _affixes, int _sellPrice, int _itemLevel)
{
GUID = _GUID;
quantity = _quantity;
rarity = _rarity;
affixes = _affixes;
sellPrice = _sellPrice;
itemLevel = _itemLevel;
}
public ItemSaveData(string _GUID, int _quantity, RarityType _rarity)
{
GUID = _GUID;
quantity = _quantity;
rarity = _rarity;
affixes = null;
sellPrice = 0;
itemLevel = 0;
}
}``` anyone know why when I set the fields to {get; private set} i get strange runtime errors but not compiler errors that i'd assume I'd get if I tried to set these somewhere?
Care to share the errors so we don't have to guess?
they are specific to my systems and dont make sense at all, invalid cast somewhere completely unrelated
i guess get private set doesnt make much sense with structs
if its completely unrelated, then what does this struct have to do with it? just show the errors
i fixed it by changing the fields, but it was an invalid cast presumably from my items being rebuilt improperly on load
maybe something to do with serialization
well, depending on which serializer you are using, properties are not serialized/deserialized
yeah, guess that makes sense
This is a repost of my question because it hasn't been answered yet.
I'm trying to make a 2D light ray simulation where light sources send out raycasts to determine how the light ray would travel around the scene. The rays can be redirected by mirrors, so some rays are made of more than one line segment. I am currently debating on the best way to draw the "light rays." I have tried using the LineRenderer and TrailRenderer components, but the problem arises when I need to draw more than one light ray per frame (I am hoping for at least several hundred). In order to start a new ray, I need to backtrack from the end of the previous one along every vertex in the ray all the way to the source and then start drawing the new line from there because the LineRenderer only draws one continuous line. From my research, it appears that the LineRenderer or a procedural mesh with MeshTopology.Lines set are the most common ways of approaching this. Is there a more proper/better way of approaching this?
hi there, anyone can help me with a unity problem?
i got a school task where a enemy has to follow you and i got that, but the enemy rotates when i freeze the rotation
the code bassicly is that enemi is moving in arround the screen untill it sports the player, but when it spots it, the enemy mades a strange flick
i dont know if its a code problen
but its seems to
Are the mirrors flat or some meshes could be convex/concave?
#💻┃code-beginner most likely. you'll need to show code
So far all of the mirrors are flat. The calculations for the reflections themselves are already being taken care of, but actually drawing every ray between the calculated points is the difficult part because using the LineRenderer to do so involves adding a lot of redundant points in order to prevent the continuous line from "looping." In the image I attached to this message, the orange line is the one I am trying to avoid by doing this.
ok, thanks
The line has to be continuous for the LineRenderer so its end loops back to the source if I don't backtrack myself along the original path.
If I'm thinking about this correctly, is the mirror shield from zelda a good reference point?
Or rather mirror puzzles as they exist in the series and other games
I think that is a fair reference. I already have the calculations for the reflections working well thanks to Unity's built-in Vector2.Reflect(). What it all boils down to is trying to find the best way to draw a lot of lines in 2D. Unity makes this surprisingly difficult, so I included all of the details about my specific issue in the original question to avoid the "asking about x but really meaning y" problem : )
The documentation says "if you need to draw two or more completely separate lines, you should use multiple GameObjects
, each with its own Line Renderer," but this would involve hundreds of GameObjects for my use case so that's why I'm trying to find an alternative.
And potentially hundreds of those objects would be active at one time?
Here's a screenshot of a prototype made outside of Unity.
There won't always be this many rays, but there's a high limit to the maximum that could be on the screen at once depending on the source and the number of sources.
Well I would say, one potential option here if you're considering performance would be to build a few simple horrible cases and check it out. In this case, it looks like maybe ~100 lines that all have two origin points (start,end).
If you built that single light core object and blasted out/set the positions of 100 LineRenderers, see how it turns out in the profiler. If you're using a raycast to get direction/reflection command you could jobify it with RaycastCommands. If the rendering of the components is the problem, I'm decently sure you could utilize DOTS but it'll be admittedly rather difficult.
I tend to agree with the multiple objects approach then optimize from there unless others have an approach that works for them. You could also store potential reflections of every reflective object based on their normal data at initialization. So instead of having to calculate the reflection, you're just activating the data from there.
And also specular reflection I think matches the incident angle and the reflected angle, so the prototype image you have would be kinda technically stylized/non-physical behavior. Am math dumb tho so pls correct.
Thank you for all of the advice! I think I have a few ideas now on how to proceed : )
A procedural mesh would be my approach. It's a bit annoying to write mesh generation code, but 2D line strips are one of the easier meshes to implement. You can easily jobify and Burst compile it. You could even move the generation to the GPU with a compute shader and draw it with Graphics.RenderPrimitivesIndirect.
Hey, so I have some 2D characters that have skeletal based animations.
They are animated even tho they are outside camera view. I was wondering how can I stop they from animating? I can't disable animator, cuz I still want to change so floats and other parameters in it even when they are outside the vision.
Maybe I can just pause the animation or smth?
I see that displabling mesh renderer stops it from rendering, so maybe I can do that
That's what this option is for 🙂
oh thanks! didnt know it existed
No sweat!
hmm, it was already enabled @past barn
but in the scene view it still was animating
In the scene view, this counts as being rendered by a camera internally. This is only going to occur in the editor. From the docs Note that animation will still be visible in the Scene view, ie it is not affected by animation culling.
Meaning at runtime with a build, you shouldn't have to stress it animating
fair
i still added one small thing
im disabling the skeletal mecanim and mesh renderer
and performance improved so i will leave it
{
int i = 0;
foreach(Transform weapon in transform)
{
if (i == selectedWeapon)
{
weapon.gameObject.SetActive(true);
}
else
{
if (Sword.activeInHierarchy && i != selectedWeapon)
{
player.SetTrigger("SwordSwitch");
}
if (AR.activeInHierarchy && i == 1)
{
M4.SetTrigger("WeaponSwitch");
}
weapon.gameObject.SetActive(false);
}
i++;
}
yield return null;
}```
Not good with coroutines,
basically a weapon switch coroutine which switches weapon.
It plays the switching animation before deactivating an object.
for some reasons the M4 animator plays both equip and unequip animations.
how do I fix this?(weaponSwitch plays the unequip anim)
Well if the Sword works then why is the animation different from the AR
rather the logic here
So, im making a sudoku game that has 4 variants(including the classic one). My problem is with checking if a made move is valid. For checking validity, my code only considers the numbers that generated initially to check if the just inputted number is repeating. Instead it should also consider the previously inputted numbers (basically it shld consider all numbers on the board at that time).
This is my board script: https://hastebin.com/share/gunicufopo.java
This is my cell script: https://hastebin.com/share/pafekipifo.csharp
Has anyone ever had issues with package cache? I was trying to help someone yesterday and every solution suggested/found did not work and I am too stubborn to just give up and must understand what is going wrong and how to fix it
im not sure I understand the problem, are you saying you dont know how to query the current state of the board for valid sudoku soluton? Like all rows/columns/nonets only contain numbers 1-9?
not understand the problem too
im sry it wasnt clear not rlly sure how to explain.
Each time the player makes a move, it is checked for validity as per the variant rules. But when it is checked for validity, it ignores the inputs(moves) that were previously made and now exist on the board.
Ill send a pic so u get it better
I first played the 1 thats next to the 8, which was a valid move. Then i played another 1 above that, which should be invalid but it still said valid because it doesnt recognise the inputted numbers while checking for validity
why are you not saving the inputted numbers in an internal array and checking that?
i dk why it is invalid to input the same number again....
btw you want the number "placed" as same way like moving piece in chess?
no
Sudoko rules, a number can only appear once in a row
the same number shldnt be repeated in a row, column, and 3x3 block
classic sudoku rules
then the state is not depend on previous input order/pattern but the board
btw where you store the number after checking IsValidMove()?
oh, i dont store the number... i thought since the cell's value updates...
yea it doesnt depend on input order
make a method in GameManager eg
public bool TrySetValue(int row,int column,int value){}
```then perform the check and setting the board[,] at the same time (if valid)
i dint rlly get it...im sry
private void UpdateCellAppearance(){
if(!board.IsValidMove(row,col,value)){
cellImage.color = Color.red;
cellText.color = Color.white;
gameManager.IncrementMistakeCount();
}
else{
cellImage.color = Color.white;
cellText.color = Color.blue;
//here
}
//unimportant codes
}
```i expect the board[,] should be updated here after checking but i dont see any code that calling GameManager to set the value of board
I have this script on my character scene where I load each of my character prefabs through inspector, and then read out details, stats for each of them on button click.
Works great the first time around when the scene first loads from the title scene. Then if I play the game, go back to the menus it loads that scene again. At that time each of those models in the script are "null". Thoughts on what I might be doing wrong?
No errors whatsoever. Just doesn't register the objects I drag through inspector
yea ur right i missed that out
how wld i go about doing that? since board[,] is in the Board script do i need to involve my GameManager script too?
i didnt read the class name and i think it is game manager.....yes not need involve game manager and use try pattern to check and set at the same call
feels like we would need to see some relevant code to get a better idea of what is going on
public TryDoSomeWork(Work work){
if(some thing goes wrong){
return false;
}else{
work.Do();
return true;
}
}
When it comes to error handling and method design in C#, the TryXXX method pattern stands out as a popular and effective strategy. As the…
also
if (Input.GetKeyDown("1")){
value = 1;
cellText.text = value.ToString();
UpdateCellAppearance();
}
if (Input.GetKeyDown("2")){
value = 2;
cellText.text = value.ToString();
UpdateCellAppearance();
}
....
```you can iterate the enum
Pretty simple stuff.
I drag and drop my prefabs for those fields.
They show up in script correctly when scene loads the first time. But if I switch scenes and come back to the same scene, all these [SerializeField] values show as "null" in script. (The inspector still shows correctly, and clicking on those prefabs takes me to the right place too)
My issue is fixed now, thx
I think we are confusing prefabs and game objects, you are assigning the game objects from the hierarchy to these slots correct? The prefabs are in your project not in your scene
They are in my scene (the grayed out ones on the left side of the screenshot)
Because I need to enable/disable them to show up in the scene when needed
likely they are destroyed when the scene unloads and the values go to null
is this a singleton by chance?
You'd need to show your code
but they're not prefabs then
No it's not a singleton, but I do only use it in one place
Sure, it's a huge class. What part of code will be helpful?
📃 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.
if they are always children of the character game object then I dont see a reason to use serializefields at all]
you can just iterate over all the children and assign them where needed
Because they are private fields, but I still want to use inspector to drag/drop them
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Another way I know to use those would be GameObject.Find() and traverse the path. I thought that was a very ineffecient way to find objects
Show what it looks like after you reload the scene?
When it's not working
This is before (when I load the scene through my title scene)
I am willing to bet that the serializefield is pointing to a game object that gets destroyed when scene unloads, then when scene reloads the newly created game objects are different instances of those game objects thus not the same ones that were serialized
And this is after. See how even other stuff is "null"
When the scene loads, would it not load the exact same way each time? Like it doesn't save any previous state right?
im not an expert when it comes to how unity handles the scene serialization /deserialization process, but if you can, dont unload this scene, instead try handling scenes loaded additively - like a title scene - so this scene doesnt get unloaded
dumb question but are you sure this is the only copy of your script in the Scene or Scenes?
correct it saves no previous state
as long as you didn't preserve this object between scenes
I think we're missing some information here
I am not sure I know how to do that.
I am 99% sure. That was one of the first things I checked, but hard to be certain
Can you tell me what steps I can take to troubleshoot/debug this?
Im surprised VS doesnt show you the references in Unity - like Rider does
one brute force way would be to use the FindObjectsOfType method and look for this script, likely a better way
This last statement really leads me to believe you are looking at a different instance of the object
A good way to check this would be:
if (characterModels[0] == null) {
Debug.Log($"Things in the list are null on me, {name}"}, gameObject);
}```
this will print when the thing happens and you'll be able to click on the log to have Unity take you to the given object
Add a Debug.Break() as well.
doing gameObject.GetInstanceID() and comparing that with the ID in the debug mode inspector is a decent idea too
I suspect you might actually have some OTHER script referring to THIS script
Where do I place that piece of code though?
and that OTHER script is the one that is DDOL
in whatever code is accessing these things and getting errors
if you DO have an error showing a full stack trace for it would also be good
Do you have other scripts that are singletons?
And are any of those referring to this one?>
Might be. Will have to check. A lot of my scripts reference each other
looking at the stack trace of any error you're getting would be a good place to start
it should show where it's being referenced from
I guess - you said no errors earlier and that the inspector also looks fine - so I'm basically confused about how you even found this issue?
And what the issue actually is? What problems it's causing?
that's the big missing picture for me
The error shows up when I try to use that null object
so you DO have an error
let's back allll the way up and see that error
and the full stack trace for it
Yes lol, but not on scene load or build. It's a run time null exception error
(do someone knows if there is a speaking channel on this server ?)
there is not
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
CrewSceneManager.PopulateCharacterDetails (System.Int32 playerIndex) (at Assets/Game/Scripts/Managers/CrewSceneManager.cs:369)
Is that the full trace?
There's got to be more
can you share the full thing
Looks like it's probably coming from:
OnCharacterClick
or
``OnCharacterClick2`
Seems to be some kind of event handler
Ahah!
onButtonClickReceiver = new SignalReceiver().SetOnSignalCallback(OnCharacterClick);```
here's the culprit
you are doing this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and you are never unsubscribing it
or ... well are you? I don't know how this "Doozy" thing works you're using
but this all points strongly towards the idea of you not properly unsubscribing this event listener
I don't know the underlying stuff either. I just use it following their documentation 😦
This example looks a little different from your code:
https://docs.doozyui.com/?docs=documentation/signals-44/signals-tutorial-1590/how-to-receive-a-signal-1449
not sure if that means yours is wrong
Thank you though. If this is pointing towards Doozy, maybe I can ask for help on their discord.
But these don't seem to match in particular:
private void OnEnable()
{
//start listening for when a UIButton is clicked
UIButton.stream.ConnectReceiver(onButtonClickReceiver);
}
private void OnDisable()
{
//stop listening for when a UIButton is clicked
onButtonClickReceiver.Disconnect();
}```
I think you would want to do whatever this is symmetrically
does this exist?
UIButton.stream.DisconnectReceiver(onButtonClickReceiver);
If you have an array that stores the length of multiple edges, would you call it edgeLengths, edgesLength or edgesLengths ?
That seems to have worked! Let me run some tests to ensure, but I think that is looking good
edgeLengths
Same for everything else ? itemPositions rather that itemsPositions ?
I'll go with it then, thanks
Thank you so damn much!! So appreciate this help. Sometimes things like these get so hard to figure out.
Made that same change in another (weapon selection script) and that is working too. So that was the cause!
No problem, have fun
Hey, so im generating navMeshSurfaces in my script, and it works fine, until i generate these lava pits. They are children of a different object than the object that is used for generating the NavMeshSurface. How would i go about excluding them from the generated NavMeshSurface?
dont want the enemies walking on lava
Navmesh obstacle component
works perfectly, thank you!
hmm, also, why would deleted objects (using Destroy (gameObject)) still affect the generated navmesh? What happens is:
- world generates with plants
- pits generate, which delete objects around it
- navmesh is generated
You can make navmesh non static. And there should be a 'carve' checkbbox too
Are you doing that all in one frame?
The physics update needs to happen between 2 and 3 in order for the colliders to really be considered gone in the physics engine
oh, yeah, its all done in the Start() function
yeah that'd be why
i see
does anyone know if theres a camera compositor solution for the standard render pipeline?
i have 2 cameras, one for the main game and the other for my weapon model and want to composite them on top of each other
not only that but Destroy itself doesn't take effect until end of frame
that makes sense
would the nonstatic navmesh update every frame or?
Hello!
How to open menu with press escape button? (script)
By checking Input.GetKeyDown()
which part are you confused about? Detecting the button press? Or opening the menu?
Is here someone working with unity?
what doesn't work? Be spectific
We're on Unity server. https://dontasktoask.com/
EXCEPTED
I think it's only when the object moves. You can define how long to wait to detect if movement has stopped
outpot write exceppted
Type it in to open it with escape
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
[SerializeField] GameObject pauseMenu;
void Update()
{
}
public void Pause()
{
pauseMenu.SetActive(true);
Time.timeScale = 0;
Cursor.visible = true;
}
public void Home()
{
SceneManager.LoadScene("MainMenu");
Time.timeScale = 1;
}
public void Resume()
{
pauseMenu.SetActive(false);
Time.timeScale = 1;
}
public void Quit()
{
Application.Quit();
}
}
Example: https://forum.unity.com/threads/if-input-getkeydown-keycode-escape-function-not-executing.1205440/
wait
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
[SerializeField] GameObject pauseMenu;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape)
}
public void Pause()
{
pauseMenu.SetActive(true);
Time.timeScale = 0;
Cursor.visible = true;
}
public void Home()
{
SceneManager.LoadScene("MainMenu");
Time.timeScale = 1;
}
public void Resume()
{
pauseMenu.SetActive(false);
Time.timeScale = 1;
}
public void Quit()
{
Application.Quit();
}
} this is good sccrippt?
What does line 12 of your script tell you?
I'm encountering an issue in Unity 2D mobile. The ball bounces correctly, but suddenly it passes through the paddle. What could be causing this problem? Sometimes, it even passes through the walls...
To open with that
turn on continuous collision detection for the ball
also make sure it's moving via physics
The error is located in line 12 of your code. Your code is not done and has syntax error. What do you want to happen when the user presses escape?
your errors are because you didn't finish writing it
To open the PauseMenu panel
Thanks, it worked great
Exaclty, but you never told the code that
can you help me finish the code?
hey everyone, so i have some movement sway code that's being run in FixedUpdate(), though it still seems like it changes intensity based on the framerate. does anyone know why this could be happening?
At least try to do it youself before you ask someone to help you do it for you 🙂
it becomes more pronounced when the framerate is low
weaponRotation.x += movementController.inputView.y * swayAmount;
weaponRotation.y += -movementController.inputView.x * swayAmount;
weaponRotation = Vector3.SmoothDamp(weaponRotation, Vector3.zero, ref weaponRotationVelocity, swaySmoothing);
newWeaponRotation = Vector3.SmoothDamp(newWeaponRotation, weaponRotation, ref newWeaponRotationVelocity, swayResetSmoothing);
wpnRot += newWeaponRotation * _swayScaler;
looks like you're reading input in FixedUpdate
that's going to cause problems
movementController.inputView is being updated every Update()
oh wait its actually using the new input system, idk how often that updates
defaultInput.Character.View.performed += e => inputView = e.ReadValue<Vector2>();
exactly
it depends on what you set it to
by default, once per frame
FixedUpdate is not once per frame
so you have a mismatch
yeah
The way to handle this would be to accumulate the input
Vector2 accumulatedViewInput;
// elsewhere
defaultInput.Character.View.performed += e => accumulatedViewInput += e.ReadValue<Vector2>();
Then in consume it all in Fixed:
void FixedUpdate() {
// handle the input
weaponRotation.x += movementController.accumulatedViewInput.y * swayAmount;
weaponRotation.y += -movementController.accumulatedViewInput.x * swayAmount;
movementController.accumulatedViewInput = Vector2.zero;
}```
this is assuming this is MOUSE input
is it mouse input?
yeah, mouse input
oh, makes sense so it takes into account every input over the time of the FixedUpdate instead of just reading it at the moment of the FixedUpdate
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
[SerializeField] GameObject pauseMenu;
public bool isPaused;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape)
{
if(isPaused)
{
Resume();
}
else
{
Pause();
}
}
}
public void Pause()
{
pauseMenu.SetActive(true);
Time.timeScale = 0f;
Cursor.visible = true;
isPaused = true;
}
public void Home()
{
SceneManager.LoadScene("MainMenu");
Time.timeScale = 1f;
}
public void Resume()
{
pauseMenu.SetActive(false);
Time.timeScale = 1f;
isPaused = false;
}
public void Quit()
{
Application.Quit();
}
}
What is the error?
mismatched parentheses here if (Input.GetKeyDown(KeyCode.Escape)
however please share your code properly !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.
⬆️ How to format your code to post it here
⬇️ How to format your !ide so you don't make basic spelling and syntax mistakes
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
So, i have a little problem.
i move an object with a method. This should trigger some onCollisionEnter into other objects, that should change a bool, that will be checked later during the first method execution.
The problem is: the program dosn't even have the time for fire the onCollisionEnter, cause he's still processing the first method. And i need to see the results of the collision method BEFORE the end of the first method. Advices?
OnCollision method are fired during the FixedUpdate loop, kind of haphazardly mixed with all the other FixedUpdates. Every function is always run to completion, nothing "interruptes" another one. If you want to pause a FixedUpdate call until an OnCollision function runs and finishes, you should stop wanting that
well i don't want to stop the fixedUpdate. My problem is like
Normal method()
{
Change an object trasform.position
if (check a bool that needs to change based on what the moved objects collided after the movement)
do things
else
do other things
}
shortly, i need to say "hey check the collisions of that object NOW"
Hi everyone, is there a way to make grappling hook work with Standard Character Controller FPS Asset...now it just wont work like grapple, it wont attach player to it and it cant swing...player just keeps going down even if he grappled. Here is grappling gun code: https://hastebin.com/share/obiyayipax.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the only way to do this is a direct physics query
you won't be able to get physics callbacks during your function
in fact for physics to work properly you cannot move the object in your function directly
you need the physics engine to move it for you
basically - your whole approach is a little backwards
just one quick note:
Time.fixedDeltaTime * 50f,```
This is literally `50 * 0.02`
that gives you 1
in other words - these are both pointless and should be deleted
Also with:
Vector3 grappleDir = (grapplePoint - transform.position).normalized;
float distance = Vector3.Distance(transform.position, grapplePoint);```
and ```cs
grappleDir * distance```
Oh okay
this is also pointless
just don't normalize it if you want the distance to be part of it
so whole fixedUpdate can be deleted
Vector3 grappleOffset = (grapplePoint - transform.position)
AddForce(grappleOffset ...)
didn't say that
how can i do that?
do you have a link on the doc? Never used that
this force the physics system to do the check?
but that wont fix my grappling problem
https://docs.unity3d.com/ScriptReference/Physics.html
Look under "Static Methods", look for "Cast"s, "Overlap"s, and "Check"s
dosn't seems to solve the problem :c
cause that methord only check if something is overlapping with something else or things like this, dosn't let the phys system actually check collisions on a given collider and call associated methods
the only thing that will do that is letting the physics simulation run
you could manually call Physics.Simulate but note that will step the entire physics simulation forward which is going to mess with everything. You'd have to commit to globally taking over the physics simulation orchstration
what about something like "wait for the phyics simulation"?
that's kinda a long story
Hi everyone, is there a way to make grappling hook work with Standard Character Controller FPS Asset...now it just wont work like grapple, it wont attach player to it and it cant swing...player just keeps going down even if he grappled. Here is grappling gun code:https://hastebin.com/share/oniharoyiv.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
we use an area attack collider that the player can move for select where the attack will be fired
the squares of the gridmap that collides with the attack area are considered "targeted" (we use OnTriggerStay for set the bool true and OnTriggerExit for false)
that's the normal attitude.
BUT in another situation we need to do with a method "move the attack area here and do things with the NOW selected squares "
a normal yeld return for waiting should work? I'm not so skilled with coroutines
what's the shape of this collider?
polygon
we need a lot of different shapes
You can do:
myCollider.transform.position = whatever;
Physics2D.SyncTransforms();
Physics2D.OverlapCollider(myCollider, filter, results);```
Is there a way to reset a field on GameObject copy?
let's try
You can change it pretty easily but to reset it you'd need a copy of whatever the "original" value is
wdym by "reset"? Copy of what? And reset to what?
the simple answer is "copy the field from the original"
this should lemme know the squares colliding the area right?
What about the coroutine method instead?
yes.
The coroutine method is jank
Like, when you copy a GameObject in Scene Hierarchy, it copies it's Component's fields from copied object too. I wan't to override that behaviour. Uh i wan't to create an un-copiable field which is should have a default value.
That way, while i having a serialized field, i could just reset it after duplication of a GameObject.
Use prefabs?
Yeha thought of it but no i just need to know if there is a way to achieve this
For this in particular you just do:
public int example;
void Reset() {
example = 5;
}```
then in the inspector you can press the ... and click "Reset" and it will set it back to 5
Thank you ❤️
does anyone know why my raycasts are acting like this? its literally hitting my player through a WALL
Hard to say without seeing the code and the inspectors of the objects involved (the wall for example)
heres my code for the monster:
Vector3 position;
bool isVisible;
Vector3 rayDir;
for (int i = 0; i < MonkeNetworkManager.Instance.RoomData.SpawnedPlayers.Count; i++)
{
position = RayShooter.transform.position;
rayDir = (MonkeNetworkManager.Instance.RoomData.SpawnedPlayers[i].fusionPlayer.Tracker.transform.position - position).normalized;
float playerDist = Vector3.Distance(MonkeNetworkManager.Instance.RoomData.SpawnedPlayers[i].fusionPlayer.Tracker.transform.position, position);
RaycastHit hitData;
isVisible = Physics.Raycast(position, rayDir, out hitData, playerDist, HitMask);
if (isVisible)
{
Debug.Log(hitData.collider.gameObject.name);
}
Debug.DrawRay(position, rayDir * Vector3.Distance(position, rayDir), isVisible ? Color.green : Color.red, 0);
}
and the inspector pics:
wekll you hid all the components of CAVE
I wanted to see what components it has on it.
oh also
the cave is on the Default layer
your layermask is only set to hit the HorrorAttackPoint layer
so it will go straight through the cave
why would it go through the cave
because you are using a layermask that excludes it, as I just said
shouldnt it hit the cave instead of passing through the wall and hitting me
no
because you are using a layermask that excludes the Default layer
include Default in the layermask if you want it to hit things in the Default layer
Because your layermask has told it to
if (Raycast(..., out hit, mask)) {
// now check if the object you hit was the player or something else.
}```
This is how your code should be^
I don't want it to because its just gonna hit the wall over and over again, as shown here
and your mask should include all layers you want it to be able to hit
that's good
that means the wall is blocking the ray
so you don't damage the player
or whatever you're doing
line of sight?
I see what you mean now
Yes
so yeah that means you don't have line of sight
if the raycast DOES hit the player, you have line of sight
if it hits anything else, or nothing, you don't have line of sight
and then should i check to make sure its hitting the player in this bool to execute what i want?
if (isVisible)
{
Debug.Log(hitData.collider.gameObject.name);
}
what i should write in the ContactFilter area? I just want to know the colliding trigger colliders...
oh i found rn ContactFilter2D().NoFilter()
should be good i guess?
you should do something like:
bool isVisible = false;
if (Physics.Raycast(...)) {
if (hit.collider.CompareTag("Player")) isVisible = true;
}
if (isVisible) {
// we hit the player.
}```
not necessarily CompareTag but however you identify the player
sure that works
if you want to hit anything and everything
I would probably make one with a layer mask at least
that filters to only your squares
ContactFilter2D filter = new();
filter.SetLayerMask(LayerMask.GetMask("SquaresLayer"));``` as a pseudocode example
I'm having some small issues with my NavMeshAgent. I want this gameObject, we'll call it "Boss", to go towards the player. It works pretty well and is very simple. However, when the player moves too high up in the air, the boss no longer moves towards the player. It instead acts weirdly and picks a semmingly random direction to travel in. Is there a way I could fix this so the boss will always move towards the player even when the player is high off of the ground?
This is what I ended up with.
Thank you for helping!
for (int i = 0; i < MonkeNetworkManager.Instance.RoomData.SpawnedPlayers.Count; i++)
{
position = RayShooter.transform.position;
rayDir = (MonkeNetworkManager.Instance.RoomData.SpawnedPlayers[i].fusionPlayer.Tracker.transform.position - position).normalized;
float playerDist = Vector3.Distance(MonkeNetworkManager.Instance.RoomData.SpawnedPlayers[i].fusionPlayer.Tracker.transform.position, position);
RaycastHit hitData;
isVisible = Physics.Raycast(position, rayDir, out hitData, playerDist, HitMask);
if (isVisible)
{
if (hitData.collider.CompareTag("Player"))
{
//Execute stuff
}
}
Debug.DrawRay(position, rayDir * Vector3.Distance(position, rayDir), isVisible ? Color.green : Color.red, 0);
}
isVisible = Physics.Raycast(position, rayDir, out hitData, playerDist, HitMask);
if (isVisible)
{
if (hitData.collider.CompareTag("Player"))```
Looks like the `isVisible` variable is extraneous here, if you care to optimize it
you could just have if (Physics.Raycast(...))
because sword plays a different animation,
It's played by the player body.
While the weapon switching is done by Iks.
The weapon sub-state plays from any state.
Maybe I can start the unequip anim from idle to weapon unequip transition.
void SetBarrierSize(float size)
{
// Assumi che 'size' sia un fattore che influisce sulla scala dell'oggetto in modo uniforme
transform.localScale = new Vector3(size * 2, transform.localScale.y, transform.localScale.z);
var spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer && spriteRenderer.sprite)
{
var boxCollider = GetComponent<BoxCollider2D>();
if (boxCollider != null)
{
// Ottieni le dimensioni dello sprite in unità mondiali
Vector2 spriteSize = spriteRenderer.sprite.bounds.size;
// Calcola un fattore di scala basato sulla scala dell'oggetto e sulle dimensioni originali dello sprite
Vector2 scale = new Vector2(transform.localScale.x / spriteRenderer.sprite.pixelsPerUnit, transform.localScale.y / spriteRenderer.sprite.pixelsPerUnit);
// Imposta le dimensioni del collider basandoti sulle dimensioni calcolate e sulla scala
boxCollider.size = spriteSize * scale;
}
}
}
it enlarges the render sprite but the box collider does not or at any rate does not do damage inside the render but only up close
Looking for some better ways to organize my scripts as its starting to get really cluttered. I was wondering how you guys organize Player data (health, stamina, etc) and the functions that impact them? Current I separate them by a script, my playerCombat script handles health, stamina, and more. It also contains the functions that impact those values. Is this better than going over and making a masterscript of all the functions and just importing them like a library?
what advantage would there be in putting them in some "masterscript" (whatever that is)?
I guess just clutter. It just feel slike alot of stuff in one file.
won't you end up with a ton of stuff in the "masterscript"?
my playerCombat script handles health, stamina, and more
What is the "and more"?
Thrust, armor, and shields. And I meant playerStatus, not combat, forgot I am using another script to handle those
well what does "handles" these things mean exactly?
Is this just a stat holder basically?
Or is this also containing a bunch of random behavior
Its meant to hold stats so I can call on them later on for the UI. But I am also adding commands like Inflict damage (may be better in my playerCombat) to inflict damage to the player
yeah the infliction of damage likely should be in a different script
that other script can read the damage amount from PlayerStatus.
Gotcha, another thing I am a bit worried about is how to handle changing this info depending on the ship the player has equiped. Should I turn the player into a prefab, and just have a Ship data script to hold info specific to that player ship prefab?