#archived-code-general
1 messages · Page 389 of 1
Makes sense
ye that worked
First time creating projectiles using Sprites here, not sure why Instantiate doesnt create 'working' projectiles
public GameObject CreateProjectile(GameObject prefab)
{
return Instantiate(prefab, ((LaserDrone)m_mob).m_attack01Origin.position, new Quaternion(), m_projectileParent);
}
private void DoAttack(Transform target)
{
if (m_attack01.interval.cur != m_attack01.interval.min) return;
var projectile = m_context.CreateProjectile(((LaserDrone)m_context.m_mob).GetAttack01Prefab());
projectile.GetComponent<RedLaserBullet>().SetTarget(target);
projectile.GetComponent<RedLaserBullet>().Init();
m_attack01.interval.Maximum();
}
If I placed the prefab directly in the scene, it would fly and move as expected, however when spawned by the Mob, it only expires naturally (as specified by an Update function in the base abstract class). It does not move, it does not even render.
Am I doing something wrong with instantiating the object?
do not use new Quaternion() use Quaternion.identity
Thank you, however they are still invisible and non-functioning
Would it help if I posted the script on the projectile?
public class RedLaserBullet : AttackProjectile
{
[SerializeField] protected float m_Speed = 4f;
protected override void Update()
{
base.Update();
m_rb.linearVelocity = transform.right * m_Speed;
}
public override void Init()
{
if (!m_target) return;
Vector3 dir = m_target.position - transform.position;
dir.y = 0f;
transform.rotation = Quaternion.LookRotation(dir);
}
}
if they are instantiated but invisible it usually means they are rotated by 180 so you are looking at the back
I see, it now appears and moves. Thank you. Will continue debugging
I have a system setup to return the transform of my friendlies. I noticed that when I calculate direction with this transform position, it would aim towards the little line under the character (I have confirmed that the transform returned is the root 'player' object). Why is this so? Should the transform position return the center of the object?
It returns the pivot of the transform, not the center
How would I find the center?
Your gizmo is set to Center in the top left corner
You could use your collider's center to calculate it
would bsing everything I create off of a pivot-based gizmo be optimal?
Or get the total bounds of your renderers and get the center from that, but might be overkill
I have three colliders, if I returned anything but the center it would be sub-optimal, do you have any suggestions on ways to retrieve the center collider? I am hoping to add other 'friendlies' that may only have 1 collider or 2, I hope not to hard code too much
Collider has a bounds property
And bounds has Encapsulate which lets you combine multiple bounds
Ah wait this is 2D?
Actually yeah should work the same in 2D
sounds great, thank you!
Hi! It is possible to get Identity provider for a user in js unity cloud code?
Does anyone know how to detect a screen tap on a mobile game running in webGL? I'm trying this but it doesn't work:
if (Input.GetKey(KeyCode.Space) || Input.touchCount > 0) {
doStuff();
}
(I'm using unity 6 if that matters)
I was thinking of just placing a transparent button over the whole game (Since this is the only interaction) But idk if that's a good way to solve this problem.
Key? Wouldn't you be waiting for a mouse click?
I also tried adding || Input.GetMouseButtonDown(0) But that also didn't work
(The space button is for when playing on desktop, need support for both platforms)
that entire namespace doesn't exist in unity 6
Ah
Yeah so that wont work lol
What about Input.GetTouch()?
have you actually tried logging the function to see if its even running ?
It works when playing on PC with the spacebar. Idk how to read console log in a game running on a server.
you don't, the logs are routed locally to console.log
the game runs locally on your machine even if its hosted else where
Can make a text element in UI and have it change runtime
Ahh ok, I'll go try some things then
yes. also #💻┃code-beginner
How to open console on mobile?
you have android?
Yes, playing on chrome browser app
there is a way to remote logging in firefox, I did it a while ago gotta find the link again
idk about chrome though, maybe they do too
found this for chrome:
In Android go to Settings, search build number, then click on it several times to activate developer mode In Android go to Settings > Developer Options > Enable usb debugging Connect to computer with usb cable In desktop Chrome type chrome://inspect , then press enter In mobile open url then check it, on this page on desktop chrome://inspect/#devices
Ok I'll try that, what should i log? Is there a way to test the input?
put the log inside the if(input statement
log it on PC webgl first, then do mobile
you might need to make it a Devbuild
I'll test this in a dev build
And ill also check for GetMouseButtonDown
They both work when simulating mobile in the browser, now ill test on my actual phone.
Ok i cant figure out the console on mobile, so ill just add an sfx to the input
UI text for runtime on android works well.
you have to use devmode and authorize pc. You never used adb before?
adb - android debug bridge
It' does the boing once and the coin a lot. So I'll add it to the other code and it will hopefully work. Thought i tried these earlier tho.
because coin just checks touches everyframe so its true every frame , buttonDown is a single frame
Hello . i want my text to enter one animation state at start and then stop and never appear again. i tried using animation but it fades the text back in, how do i fix that
wait *db is debug bridge? i thought it was just __d__e__b__ug 😭
Do you mean it's looping now. You can disable looping
yeah its looping
Doubleclick on animation_text and disable it
lol they just decided , hey lets shorten this word instead of acronym
i just kinda accepted the g* suite of stuff
gcc - c compiler
g++ - ++ compiler
gdb - debugger
thanks bro u saved me some time
Also had trouble finding that first lol, it's kinda hidden
Using it like this doesn't work :(
I'll check if it works for the jump code tho
To see what is the problem
if you're waiting for it, you'll need && for the negated condition
!(a || b) = !a && !b, by de morgan
Oh yeah that's true wow
if you're not familiar with de morgan, try stepping through the logic:
- to continue with the loop, either:
- space is not pressed.
- screen is not touched.
a desktop user will not create touches, so the latter will always be true.
a mobile user will not press space, so the former will always be true.
hence, the loop will always continue
Yeah the input works for the jump code.... So the input wan't the issue AAAAA
Thanks for helping tho!
Yeah, made a mistake there lol, thanks for letting me know!
I'm scrolled way up, and only seeing a couple msgs... there's no need to use a browser for debugging Android. There's a package called 'Android Logcat' that does it much easier.
There's also a free asset on the store called 'Luna Console' which puts a console in app
Oh nice. I didn't think logcat worked with debugging browser logs. Good to know these new packages exist 🙂
I may have missed relevant info.. that makes what I said null
I have a project done on Windows. I opened it up on a Mac, but for some reason, Vector3 positions are wonky on the Mac. Projectiles that should be spawning at a firePoint.position are appearing at completely different points in the level
Is this some sort of bug when transferring projects between Windows and Mac?
not at all. I do it daily
the transfer is just a coincidence, not a cause
are you certain you're checking the correct scene and are the scripts are up to date ?
Yup, I haven't really changed anything in the scripts at all
Getting an annoying "fake" shader error (i.e. an error that isn't actually breaking anything in my shader) about SampleMainLightCookie being undeclared.
This is the code from the hlsl file that the error is pointing to:
void MainLightCookie_float(float3 WorldPos, out float3 Cookie)
{
Cookie = 1;
#if defined(_LIGHT_COOKIES)
Cookie = SampleMainLightCookie(WorldPos);
#endif
}
and yes, despite this error, the mainlight cookie is working fine and affects my shaders.
what exactly is the new poisition they go to ? Vector3 would not change how it functions
This is probably a very simple answer but would anybody know why when I put my PlayerJump function into FixedUpdate it takes multiple pressed of the key for the function to fire off? (The GetInput function is in Update, not Fixed Update.)
fixedupdate and update run at different rates
by the time fixedupdate is called, update may have been called again, and in that next frame, jump might not have been pressed, so jumpInput would be reset
Do you recommend both being in FixedUpdate or Update? I know it’s advised to keep all physics based functions in FixedUpdates to limit disparities across instances of the game.
since it's a button-type input, setting the velocity would be done as the input is recieved, ie per-frame
Input goes in Update
Physics goes in FixedUpdate
time-based stuff goes in fixedupdate
simply setting a velocity isn't time-based
You need to store the player's intention in Update, and handle that in FixedUpdate
if you were doing, say, velocity += acceleration, that would need to be done in fixedupdate
or that friction, that'd also need to be in fixedupdate (but why do you have that instead of just... applying friction/drag on the rigidbody)
what exactly is the new poisition they
It’s just for a bit more control over the friction without having a global effect in game. I might scrap it later on but just threw it in there for prototyping.
Sorry to ask another question but what is a simple explanation as to why the character horizontal movement works fine with the input in Update and the PlayerMovement function in FixedUpdate but the PlayerJump function does not? Is it because it’s a button hold vs a button press?
probably
in short do not use FixedUpdate for user input.
it is only 50 calles per second
Update is much more depending on your specs
don't think about the physical buttons, think about how they're used
movement is an axis, it's a constant value
jumping is a button, it's an instantaneous event
input is frame-bound, so that constant value is updated once per frame
but the instantaneous button will only last 1 frame
anybody know how to get a linear acceleration to a rigid body without directly modifying its velocity?
the AddForce method
yea but that is m/s^2
that's what acceleration is
yea im asking if there is a way to create a acceleration that is linear m/s
yea ik
"linear" just means directional and not rotational
im asking if there is a way to change the acceleration to m/s
yea lemme try that
there's a table for that somewhere
Force is T^-2 L^1 M^1 (kg m/s^2, N)
Impulse (Momentum) is T^-1 L^1 M^1 (kg m/s)
Acceleration is T^-2 L^1 (m/s^2)
Velocity is T^-1 L^1 (m/s)
yea im looking back into impulse and Force mode bc i had bad information before
How would I be able to add in a slider for the sfx and background music of my game? I have been trying to wrap my head around how to link the slider audio mixer and the game all together but I can't seem to figure it out
its one float, not much to figure out
also probably a #💻┃code-beginner question tbh
https://paste.ofcode.org/Xu2JRBYzEGhcjL7ugmMZWa
So i have this script, i found out a few things in Unity. See screenshot. Bridge is parent to a collection of objects who forms the 3d object Bridge, Bridge is also the child of another object.
Objects of Schip which is also the child of Boot Story.
I have no clue how to fix this.
The objects of bridge should ALL be inactive when BargeBarge.To and BootBoot.To hits the objects of bridge. when they don't collide anymore the bridge is active again.
What am i doing wrong?
bridge itself has a boxcollider with the script attached. it's supposed to dissapear when it hits the bridge.
forgot to add the hierarchy oops
Hello, I have a text child of my button is there a way to rotate the button without rotating the text ?
button.image.transform.rotation
ive tried to rotate directly the image of the button but it doesnt work
don't cross-post
Is there a way to raycast from camera, via mouse position, onto the navmesh?
I want to have my right-click to ignore all entities in the world, and just move to the raycast intersection on the nav mesh.
well, i tried this, but read what it does
oh yeah, between two points
it's about checking if the agent can move towards the point
you probably need to hit the surfaces themselves since the nav mesh isn't a collider anyway
you might be able to grab the nav mesh and build a collider from it and cast against that
but it feels simpler to just hit the actual surfaces
that's what i do atm
directly casting onto the navmesh would be better though ^^
thats why i asked
yeah, I'm not sure I agree but I don't have a strong argument either way
I feel a little bit like coupling those things so tightly isn't actually what you want long term
because you end up in situations where, like, the player thinks they are targeting something visual which they'd expect to be blocking, but you have no way of knowing that because your are only able to query against your nav mesh and not the world at large
ideal function would be "NavMesh.FindClosestPointOnMesh(Ray ray);"
could someone check my issue?
hmmm wouldn't the closest point on the mesh always be the same at all points along the ray?
this is good though. cause left click checks for objects. but right click should kinda be a 100% "moving" instruction
e.g. what if you want to move to a point that is in the middle of a group of units?
yeah I can see the logic, I just feel like in reality it ends up being extra effort to give yourself less flexibility long-term
that's kind of what I'm saying, that the targeting layer doesn't necessarily map directly to anything that already exists (visual world, nav mesh, ground plane, wahtever) and so maybe should be its own thing
anyway that's probably not very useful but makes me want to look at a higher level solution
back to this though, i'm not sure you need the ray at all
you can just query the closest point to where you'd start your ray
since how my game is basically on a flat surface, i might get away by just raycasting onto a plane, just need to rework it whenever i decide to add slopes or so ^^
it's kind of a 2.5D game, or i could just abuse the terrain component as the ground and raycast all movement instructions on terrain only
Hi! Could you please give me some links about rigid body/transform? I'm making game without physics, so I assume I don't need rigid body in this case, but I saw some info that moving objects via tranform.position is not a good approach and even may impact performance. Another issue I have if I don't use rigid body, I had to use colliders and OnTriggerEvent and it doesn't work with OOTB unity layers configurations. Or may be someone can clarify those points to me -)
There's nothing wrong with moving an object via the Transform, that's what the Rigidbody does under the hood.
But if you want to use collision callbacks and colliders then you are mistaken about your game not using physics
You are indeed using physics in that case
My use case is - I'm doing simple space shooter, there will be bullets and enemies. Yes, those will collide, but on collision will be destroyed. So I don't want to have interaction in terms of bouncing off or something like this in those cases. I feel in this case I don't need rigid body and that's why I though no need physics (since collider responsible for collision detection).
I'm probably missing something big here -) haha )
a rigidbody is also used for detecting and firing trigger events
you can set it to "kinematic" to disable force simulation
you can do your whole thing without rigidbodies only if your entire collision detection is implemented via ray- and overlap casts on trigger colliders.
That's all physics what you're describing
You're just talking about using trigger colliders instead of non triggers
And whenever you have moving objects with colliders, it's best practice to use a Rigidbody
So it's better to add collider + rigid body, set body to kinematic so it won't trigger physics and move object via rigid body? Is that's right?
No, use a trigger collider
Not kinematic
So basically I do this if I understood correctly.
Hey, I'm using animation rigging IK, which works on top of the animator. I use no actual animations, I have an empty animation controller, and no avatar. I connect objects at runtime, filling out premade ik constraints, add those rigs to the rig builder and rebuild. This works fine. But when I remove game objects, and remove rigs from the rig builder, I get could not resolve ... because it is not a child Transform in the Animator hierarchy It still appears to be working but is there anything I could do to supress the warnings? or maybe there's some proper way to clear the animator state?
I'm also have a question about configuring game level. For example I do plan to have several groups of enemies to spawn withing level at different positions and different time. As I see it I implement scriptable object and put configuration there with data like enemy config, spawn position, spawn time etc.
But at the same time I feel configuring it via SO is a bit cumbersome. Is there good approaches to do such configs? I have something like this for now, but position as Vector3 already makes me a bit nervous. Though If I drag and drop transform from scene, I feel it's also will be not good since there may be no transform on scene later.
I search some in internet, but usually it's simple guides how to create game object or spawn 1 enemy via factory, but this is already done from my side.
Is there may be some good approaches to do this? Could you share with me please?
you're making SO's so you're comfortable with code, my general approach is try to use as much unity as you can. Unity already has a way to store enemy spawn points in a level: you put a game object in a scene. Come up with your own systems if a straightforward way via the editor is not enough and you're solving some problem.
For something like that, it probably makes sense to place WaveSpawners in the scene and configure those (or something similar). Basically make use of the scene to position things since that's what it's for and that's the main 'important' thing you're trying to set up (and more importantly, want to be able to visualize)
But won't I have to create new scene for each level in this case? While I could've reused one scene for several levels? Or I'm overthinking it?
I expect you would want a scene per level
everything depends on what you're making and how you want to work, but that's a lot of what scenes are for
if you wanted, you could use prefabs instead
a prefab per level, and the prefab lives at the origin and has the setup for a given level
whatever feels better to you
If you want different, but hand placed, enemy configurations on the same level geometry you can use additive scene loading. Have a scene with the geometry, then open a new scene with just the enemy placement.
It's simple space shooter, so I have player at bottom enemies from top-and sides. While background is scrolling under player. That's why I though My scene basically all in camera all the time and enemies created outside of view port.
ah yeah, that's kind of a toss up for me as to if it's worth doing any of that
one solution is to decide on x spawn points and name/position them
and then in your config, pick the spawn from a dropdown
that way you aren't storing all these one-off positions and can move an entire class of spawns if you need to
And in this case it's better use prefab I believe so it's on scene?
well in this case you'd just have the one scene for everything
and then you'd use SOs to configure your levels like you are now, you'd just use predefined, named spawns instead of setting it manually for every spawn
Got it. This is much better from what I have now. Since manually entering coordinates looks like very bad thing 🙂
Thank you!
I will check this approach too. I'm not sure if it will suit me here, but it's totaly new thing to me with additive scene loadings.
yeah, you just need a reasonable abstraction around 'where are they spawning' and that could be a whole scene view, but that seems more cumbersome than it's worth
https://issuetracker.unity3d.com/issues/could-not-resolve-dot-dot-dot-because-it-is-not-a-child-transform-in-the-animator-hierarchy-warnings-after-animations-play I guess this is not meant to run at runtime by design. I'll live with the warnings, need to check if this actually works in a build. I have a backup plan to have an invisible skeleton animate / rig animate, and I'll attach my runtime parts to the invisible skeleton.
Thank you for posting your research 🙂 How many times we saw "I solved it" without explanation in some famous site about coding -)
Anyone ever use the Blackboard design pattern?
Probably many people. Without even realizing it.
Sure, mostly for animations, AI and proc gen
Was thinking about using it for card game effects. Something I can just set random values to so multiple parts of an effect can communicate.
Would the values have different datatypes or are they all int or float?
Different data types likely.
For example imagine an effect that was.
-
Deal 1 damage for each card drawn this turn.
-
One part of the effect would listen for CardDrawn events and tick up some number in the blackboard.
-
Another part of the effect would set the value back to 0 at the end of your turn.
-
The active part of the effect would look at this value in the blackboard to determine the damage it needs to deal.
Sounds sensible to me
Ya the real question is... do I just go with <string, object> >_>
I usually have different dictionaries for different datatypes
And then have functions like SetInt/GetInt/SetFloat etc. to access them
Much like materials or the animator does it
I assume you would only have a few datatypes anyway
Hello, I need some help figuring out a problem with my animators. My random character builder has a "build" button in the inspector that spawns in the module parts and assigns their skinned mesh renderers to adhere to the main rig. The issue is that if I press this button and spawn the gear out of playmode, the character does not animate, not even the bones. I don't know what could be causing this. Can someone explain what could cause an animator to not animate bones?
@dawn nebula you can always have a <key, object> for special cases
Or you can go completely with object if it is not performance critical
Show us how you are doing it currently?
Doing what? Building the character?
The code you use to assign the gear
void Attach(SkinnedMeshRenderer targetSkin, Transform rootBone) {
var newBones = new Transform[targetSkin.bones.Length];
for (int i = 0; i < targetSkin.bones.Length; i++) {
foreach (var newBone in rootBone.GetComponentsInChildren<Transform>()) {
if (newBone.name == targetSkin.bones[i].name) { newBones[i] = newBone; }
}
}
targetSkin.bones = newBones;
}```
It was from a code monkey video, I believe
Moreover, if I just drag a module prefab into the hierarchy of the character during runtime with no code touching it, it animates
So the issue probably lies with what bones are affected by the animator, but I don't know what determines that
So you mean if you assign the renderers in edit mode and enter playmode, those renderers dont follow the animations?
Nothing follows the animations. This isn't a problem with the skinned mesh renderer attachment, because that correctly attaches the renderer to the bones. The bones themselves aren't animating.
Well, it probably is something wrong with the attachment
So your character isnt animating at all
Nope. Except for the red IK bones which aren't used or touched by anything
Thought that might be relevant
Main concern is boxing and unboxing of value types, ya?
Yea
Also can use enum key instead of string key
Makes it easier to develop too - getting intellisense for the key names etc.
🤔Look for any warnings or errors when you play
Are you using animation rigging or other anim packages?
Not exactly sure but maybe the avatar?
Oh thank god it fixed itself randomly
Thanks guys
I genuinely touched nothing, I think I disabled and then enabled a script, it works now
I love it when god fixes my bugs for me
Okay I think I figured out the cause of this. The presence of the module's own rig makes the animator animate it over the main rig. When not present, the correct bones animate
What causes this preference? no idea
Also, when I spawn it in during runtime, the bones animate correctly. Wtf.
Does that hierarchy have more than 1 animator?
I could maybe just create a generic wrapper around the value (like BlackboardEntry<T>) and put it in the blackboard. Still have a <string, object> and just cast the object into the proper type.
No boxing I think?
Like this
Okay so it doesn't work if I just spawn it in normally. But when ran through the script, it works. Something in this method causes the bones to correctly animate (not the mesh renderer, that works fine)
You could have cs public class BlackboardEntryBaseAndcs public class BlackboardEntry<T> : BlackboardEntryBase
Then you can use <string, BlackBoardEntryBase> instead of <string, object>
What's the benefit?
Pretty sure that each object will be boxed here
Why? BlackboardEntry<T> is a class. 🤔
The inheritance would just be
BlackboardEntry<T> -> BlackboardEntryBase -> object
instead of
BlackboardEntry<T> -> object
What you are suggesting is probably fine
I hope so 😛
By the way, tell codemonkey that this code is garbage
SkinnedMeshRenderer.bones creates a new array every time you call it
What's the right way?
I'm just saying you should at least cache the array instead of calling bones again each iteration
But it works? Clearly it's referencing something
I didn't say it doesn't work, it's just unnecessarily expensive
I'll cache it
Say you have 50 bones, it allocates a new 50 bone array 50 times in that loop
Sounds good to me
Yeah wow no wonder I began seeing lag spikes at 20 spawns
Looked at my old code and this is what i did in my project to copy bones for clothing:cs selfRenderer.bones = sourceRenderer.bones; selfRenderer.rootBone = sourceRenderer.rootBone;
But maybe the name checking in codemonkey's code is there for a reason... Like if the rigs are different
Not sure
Well, it works for me
Also why set root bone?
Uhh why can't I find root bone on the docs? 🤔
Oh it's because there is no source renderer.
You're trying to put a skinned mesh renderer on a skeleton
Shoulda clarified, the "source renderer" is the character's skinned mesh renderer here
Since it always has the correct bones I use that
I could tell, but the character does not have a skinned mesh renderer before it gets its parts
Okay, well, that would make it a lot easier and probably more efficient
To have a pre-existing rig to copy stuff from
I'll do that
After I get the fucking thing to animate at all
So if I change the name of the root bone to penis then it chooses to animate the main rig
we did it
Btw found the doc for root bone, for some reason it's only in the Manual and not in the Script reference
Seems like it's just for the bounds
hey peeps, having some weirdness in unity atm, needing some help, animation rigging is doing absolotely nothing
i added Rig 1 and HeadLook myself
then added the head node to the Tip property, used the 3 dot menu to auto set it up
i press play, move the headlook target, absolutely nothing happens at all
ive tried a few different ways to set this up over the week and had zero luck, but the unity import shows that the model is rigged fine in the humanoid setup menu, its really weird, like ive used this before and now its just not working at all, im sort of tempted to just write my own code to handle this because its just refusing to work
huh, if i try to use the rig setup options at the top of the screen, then run the game it just fully crashes, something is super messed up on my end and this is just an empty project with a humanoid in it
Check the logs after you crash, maybe some useful info there. This is more of an #🏃┃animation question tho
absolutely nothing of use to me in any logs
@hexed pecan I did end up creating a base class.
Was useful for defining a copy method for when I wanted to duplicate entries across 2 blackboards.
rubber ducky magic happened, after a solid week of it not working, i complain once, do exactly what i did before and it works
love that, thanks unity
now i just gotta debug why the character is in the floor hahaha
Use a stable version of anim rigging and unity if you aren't already
i am using the latest on both
Hey guys (:
I'm doing a TED talk in english class about problem solving, and I'd be very happy if you answered this short survey for it.
{
// Ensure there is a path and the agent is set to move
if (ConnectionArray.Count == 0 || !agentMove) return;
// Get the current target position
currentTargetPos = ConnectionArray[currentTarget].ToNode.transform.position;
LocatioOfNextNode = currentTargetPos.ToString();
// Move the car towards the current target position
Vector3 direction = (currentTargetPos - transform.position).normalized;
transform.position += direction * currentSpeed * Time.deltaTime;
// Rotate the car smoothly to face the direction of movement
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
// Debug.Log("currentTargetPos : "+currentTargetPos);
// Debug.Log("Direction :"+ direction);
// Debug.Log("currentTrget : "+currentTarget);
if (Vector3.Distance(transform.position, currentTargetPos) < 0.5f)
{
currentTarget += moveDirection;
Debug.Log("CurrentTarget : " + currentTarget);
Debug.Log("ConnectionCount : " + ConnectionArray.Count);
if (currentTarget == ConnectionArray.Count)
{
Reached = "Location reached ! Returning To start";
}
// if (ConnectionArray.Count <= currentTarget)
// {
// moveDirection = -1; // Reverse
// currentTarget = ConnectionArray.Count; // Set to last index
// Debug.Log("CurrentTarget : "+currentTarget);
// Debug.Log("ConnectionCount : "+ConnectionArray.Count);
// if (currentTarget <=-1)
// {
// Reached = "Reached start!";
// agentMove = false;
// }
// }
}
}```
hello i need help im using astar algorithm to path find the shortest path and on that path i have to move a car from start to end and back to start while returning to start i face a problem of the car stopping just before the start can any one help me
Is that ai generated code? The answer to your question is very simple if you read the code and understand what it does.
i tryed on my own it didnt work so i used chat gpt
Read and understand the code. Or ask chat gpt for clarification.
ok but u understand my problem whats happning right ?
ill read it then please help me if i cant fix it
Yes. As I said, it's very simple. Check the condition that you check to keep moving.
i dont get it please help me
your talking about if (ConnectionArray.Count == 0 || !agentMove) return; yess but even without it it incounters the same problem
while counting the currentTarget it doesnot count the start as a target so while returning it stops at the node which it started counting on
Then just add the start to the nodes list
how
its not ccounting the start as a location
it counts the location from the start location so the location of start is not in the array
Im a bit confused, are you creating a presentation in the same structure as a TED talk for your class or are you reviewing an existing TED talk and incorporating it in your research? And what kind of information are you hoping this survey will help with? From reading the questions it sounds a bit bias toward correlating problem solving being a transferrable skill in other non-programming industries?
The survey will give me statistics to present in the ted talk
To strengthen my point
the pathfindinglist.cs calculates the node location it starts from the start to the next node so it doesnot have the location of the start node
if node 0 is my start then the program is calculating the location of node 1 and puting it in index 0 so in the list there is no location data for node 0
if i reverse the array to move back then it will move to index 0 which has the location of node 1 not node 0
Ah I see, so this is a presentation your giving in the same structure as a TED talk? If this is for research, it may also help to look into the neural activity related to problem solving and reasoning, if you havnt already
I'll look into that, although this is a 5 minute talk so I'm not sure if I'd be able to fit that in
Hello, So ive been making this quiz game in unity and I really wanted help with this problem Im dealing with. Basically I have a script which loads scriptable objects as questions from a resource folder. I find it tedious to make a question one by on, so is there a way for the game to load questions from a script that has question all in one place?
ive been at it all day
Ah, didnt have full context when you said "TED Talk", most I seen are usually around 15 minutes on the short end, and often try to focus on scientific research (although sometimes it literally is just a personal story with no stats or science) - for a 5 min presentation neural science might be too deep of a topic to explore, but ill check out your survey
You are the one that created the original script ? You can do whatever you want. If you want to create a QuestionList which hold the question you are free to do so.
However, given the nature of a question, I would believe it is wiser to keep it divided by themselves. Obviously, it might be tedious to create them but so is 100'000 others manipulation. Not saying that it needs to be, but I'm saying that, sometimes, it might be justified.
why use an SO at all? You could load them from a text file
i agree, just use a json file or something for your questions. no need for SOs in this case
asked this in the talk channel but maybe it'll get more traction here with code focused people -
does the github npm package registry still not play well with UPM? i've tried adding it as scoped registry & doing the usual auth with .npmrc, & packages are published without the @orgscope/packagename to play along with the specific naming conventions of unity, but unity still fails to pull them due to missing auth
Haven't tried the github one, but we're using verdaccio and it works fine at least. No idea what would be different
yeah have used both verdaccio hosted internally, & gitlab npm registry. Github is the one that seems to play up, according to previous posts on the forums
might just self host and deal with the maintenance myself
Not really Code, but are Sprites stored in the VRam? Or how can i store them in the VRam?
they need to be in vram to be rendered at all, that's usually handled automatically
are you experiencing bottlenecks with cpu/gpu communication?
No, but im making a game For a Console where VRam and Memory is Crucial, so i wanted to know If Sprites are stored in the VRam, Normal RAM, or in both.
unless you have tons of 4k sprites, you don't need to worry about that, usually leaving it to the automatic unity systems is best for smaller projects.
If you DO have issues, then put them in an atlas, and if that doesn't solve the issues, look into addressables and load in the sprites you need, as you go
Alright, thanks!
but it also depends on which console exaclty you're building
if it's an ARM based console, don't even bother, unless you're exceeding the overall memory, then addressables
or fix your issue elsewhere
Alright
not a code question. #🎥┃cinemachine
Library\PackageCache\com.unity.ugui\Runtime\UGUI\UI\Core\Layout\LayoutRebuilder.cs(241,26): error CS1061: 'ObjectPool<LayoutRebuilder>' does not contain a definition for 'Release' and no accessible extension method 'Release' accepting a first argument of type 'ObjectPool<LayoutRebuilder>' could be found (are you missing a using directive or an assembly reference?)
Getting a weird error... not sure why. Just imported the unity ui package.
Does somebody know why this line gives me an InvalidCastException? I genuinely have no single clue.
redBlock is of type RedGreenCube
RedGreenCube tmpTestBlock = Instantiate(redBlock, spawnPoint, Quaternion.identity);
Hello i don t see why i get this error:
a powerful website for storing and sharing text and code snippets. completely free and open source.
because Instantiate returns Object
NullReferenceException: Object reference not set to an instance of an object
PlaceingObj.cs:line 61
How could I attempt to cast it?
either cast or use as keyword
preview.UpdatePosition(mousePosition);
preview is null
I tried RedGreenCube tmpTestBlock = (RedGreenCube) Instantiate(redBlock, spawnPoint, Quaternion.identity); and RedGreenCube tmpTestBlock = Instantiate(redBlock, spawnPoint, Quaternion.identity) as redGreenCube;
I am not sure how to do it, since my IDE doesn't show it as an error
then you need to configure your !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
These ones still don't work though @knotty sun And I am using Visual Studio installed via Unity Hub and normally it shows errors
this
RedGreenCube tmpTestBlock = Instantiate(redBlock, spawnPoint, Quaternion.identity) as redGreenCube;
should definitely show an error
it says cast is redundant in my IDE
that is not an error
RedGreenCube tmpTestBlock = Instantiate(redBlock, spawnPoint, Quaternion.identity);
In my IDE it shows without errors, yet in Unity it gives me the invalidcasterror. And I don't know how to change this line to resolve the error in Unity when I try to execute this line
My IDE is both autocompleting code as well as showing errors of other types though
but why is it null?
because you never assign anything to the variable
Debug.Log($"redBlock {redBlock.GetType()}");
before the instantiate
redBlock RedGreenCube
UnityEngine.Debug:Log (object)
then I cant see how that line is throwing an invalid cast exception. Screenshot the error and stack trace
Can super help me with a simple script
I need a script for a sphere that knows where it is hit when it is hit and gives a lot of velocity in that direction
I think I figured it out, I was writing code for the Editor and there was a typemismatched gameObject in the Inspector
That's why the IDE didn't show it as an error, but Unity did
Thanks for the help though
Use oncollision method
What’s that?
something for you to research
can classes from one script have instances made of them in any other script? if not, how do i make it so i can create instances of my class in any of my scripts?
yes. what i'm guessing you are actually referring to though is a nested class, and that is still possible as long as it is public. but outside of the class it is nested inside of it would be called OuterClass.NestedClass rather than just NestedClass
for example:
public class SomeClass
{
public void Start()
{
var x = AnotherOne();
}
public class AnotherOne { }
}
public class Other
{
public void Start()
{
var x = SomeClass.AnotherOne();
}
}
call it's constructor in that method?
make the method static. return the new instance
static MyClass MyMethod() {
MyClass myClass = new MyClass();
// Do stuff
return myClass;
}
okay i create a singular instance by writing Atom x = new Atom(); but i need to create a completely new instance each time the method is called
like i cant repeat Atom x = new Atom(); multiple times?
so put that line inside the method
i think you have to learn some c# basics
Look how simple. First & second result https://www.google.com/search?q=oncollision+method+unity
If I wanted to create a google maps like effect where the zoom seems to happen from where ever the cursor (PC) or pinch center (smart phone) is with a perspective camera in Unity, how would I go about doing this? Or does anyone know of a project that does this?
Thanks
Probably just lerp/move the position of the camera towards a point above the target point, while also zooming.
Hey , how can i trigger a InputSystem action via script
feel the need for that is a x/y problem
For example when u store a input action reference in a field , when button pressed i want to send related data to that reference how can i do that
I don't think that's an intended use case for the input system. It's supposed to receive the input from input devices. Not your project code.
@cosmic rain I guess it's my fault I felt it a little late 
Now all I do is to trigger the event called by the input action via the event bus and I will not interfere with the rest
thanks
ideas on how to make this not clipping through but getting over when objects touch?
a powerful website for storing and sharing text and code snippets. completely free and open source.
I've heard alot of bad thing abouts goap's preformance as a solution for enemy ai, is it really that bad? or is it just like hated for some reason
heard from where ? grape vine?
whats the legitmate arguement made there?
I dont know I've just read some people saying that its slow so im just double checking if its true here
"some people"
idk just like on forums and stuff
we can't verify or dispute claims when we don't know what those claims are or where they're from
very subjective
goap v3?
How should we know unless someone here purchased it
chances are 70% of people here built their own
at least I did
fair fair
if its free , try it I suppose.
ok thanks for the insight
When you move an object, add some function to determine the correct target position. Something like:
private Vector3 GetTargetPosition(Vector3 desiredPosition) {...}
Into that function you input the position you would like to place your object. Then you loop over all other objects within your database. Compare renderer bounds to see if there is an overlap with any other object. If there is no overlap, just return the desiredPosition. If there is an overlap, "depenetrate" the transparent object and return the depenetrated position. There are different ways of how this can be done:
- Physics.ComputePenetration (requires your objects to have colliders)
- Compare bounds to compute offsets
You'd also need to think about into which direction you'd want to depenetrate. Physics.CoputePenetration takes the shortest path out of another collider. You could limit that to the X/Z plane in case your level is always flat. This also means that the transparent object will only "snap" to the other side of the placed object if your mouse is on the other half of the already placed object. For earlier snapping to the other side, alter your desiredPosition before depenetration depending on the direction of movement (= velcotiy) of your transparent object, so that the position you depenetrate is already on the other half of the object you want to get out of.
Besides, please use some code conventions: you mix different capitalizations, indentations are all over the place and you miss line breaks between functions, making it hard to read
good luck 🙂
Hello, i'm trying to create a RPG but i'm having an issue on how to code design my abilities.
Currently:
a hero contains abilities,
an ability contains a cooldown, a cost, ref to the owner and a list of effects
an effect can be a damaging effect, a modify stats effect and other...
Currently when learning an ability you get a new instance of it.
Now my problem is i want to implement modifiers to my abilities. An ability can be modified by a talent tree, an effect from an equipment or anything else.
But what is the best way to implement this ?
You could look into something like this: https://www.youtube.com/watch?v=gYYfrtq6MrA
Dive into Player Stats and Modifiers using the Broker Chain pattern! Uncover how this powerful design pattern can streamline your coding process and enhance game mechanics. Get ready to supercharge your programming skills and bring your game ideas to life like never before!
Remember! In C#, Delegates are invoked in the order they are added to t...
Essentially your system will contain multiple sub systems, you have your core ability system and then you would need some sort of stat/modifier system and It's this stat/modifier system that would be responsible for applying effects to your abilities, talents and equipment. There are many ways to implement and handle a system like this but this is just one approach that could help you implement and maintain such a system
it seems really interesting, i'll try it out, thx !
Hi all, I need help: transform.SetParent issue, I am calling it with 2nd argument WorldPositionStays=false, and while it gets parented the behavior is very weird. Some of the objects dont follow as they should but rather move "inverse" to the parent. Not sure if this is a code issue or editor issue. Other objects in the same loop get parented and follow correctly. It's weird. https://www.youtube.com/watch?v=AvSL-7KLjcw
the jittering looks like there is some collision happening for the plates in your right hand and PhysX tries to depenetrate them. Try activate the physics debug mode to see colliders. Other than that, check scaling (maybe somehwere is a negative scaling, maybe in your right hand?)
looks cool btw, I hope you can shatter those plates and throw them around 😄
thank you. i think maybe you mean left hand? that is what I used in the video. Also I do isKinematic=true on the plates since they say not to do parenting otherwise. the jitteryness is I think just how it always is with XR grabbables. It's always looked like that. I did check hands for negative scaling but none, neither in the plates. I'm not sure if you'd continue to suggest the physics debug window, though I'm not too experienced with it or what to look for. And I'm glad you like it.
private void OnDrawGizmos()
{
Debug.Log("Drawing Gizmos");
Gizmos.color = Color.red;
foreach (var point in splinePoints)
{
Gizmos.DrawSphere(point, 0.1f);
Debug.Log(point);
}
Gizmos.color = Color.blue;
for (int i = 0; i < splinePoints.Count; i++)
{
Vector3 currentPoint = splinePoints[i];
Vector3 nextPoint = splinePoints[(i + 1) % splinePoints.Count];
Gizmos.DrawLine(currentPoint, nextPoint);
}
}
I'm trying to figure out why my gismos are not drawn, I'm trying to crate a spline tool and want to see points in scene, This scripts is in all of my objects
any ideas?
are the gizmos enabled in the editor
yes, when i test it with a simple sphere draw its drawing it
I'm expecting points on my ring object.
oh okay, maybe the video is deceiving then, it looked partly correctly. If they are kinematic then yes, physics interactions shouldn't be a problem...
It does look to me like picking up a single plate is fine, but multiple cause errors. I'd say log local and worldspace positions of plates and hand before and after parenting. Maybe you exit somewhere too early in your loop?
Actually, why do you call the parenting with WorldPositionStays=false? This might cause position errors upon picking it up
yeah -- If you do this, the local position of the object will be preserved
which could give you a very silly offset from the thing you parent it to
Also, whenever you're having problems with a Rigidbody not respecting the position you try to put it in, take a look at its interpolation mode
If the rigidbody is set to interpolate, it will overwrite the transform's position and rotation every frame
If it's not set to interpolate, it will wind up reading back the transform's position during the physics update
(and thus actually use it)
im going insane, i have been debugging the same script for 3 hours, still doesnt work. it works perfectly fine in the unity editor, but for some bumfuck reason, doesnt work in build. wtf???
here is said script:
link that on a paste site -- !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.
and what problem are you having? is it not logging any thing at all, or is it just failing to rotate correctly?
it rotates perfectly fine, it hits the player perfectly fine, but only in the unity player. in the build, it also rotates normally, but it just doesnt hit the player. the Shoot() function doesnt trigger at all.
Does "yaya" get logged in the built game when the player overlaps the laser?
let me see
You may want to log the object you hit, in case there are tons of trigger overlaps
it now works???
i built a dev build
it worked
then i built a reg build
and it works?????
i did not change any scripts
wow buddy no swearing
what the heck?
much better

that happens from time to time, haha
It's possible you wound up running an older build, or that you just fixed it by accident
or...it's a hard-to-reproduce bug that involves the exact order of object creation or some weird timing quirk

Is anybody aware of any framings that challenge the "XY problem"? I'm asking because I think that a situation can sometimes accurately be described as an XY problem, but not always!
well that's neither unity related nor code related. but you could give this a read and then ask for futher help in some other server where offtopic/social dicussions are permitted: https://xyproblem.info
mmm, yeah, that's true, okay will do
how can i make my ball in my game move very fast when I hit it
depends on how you're hitting it
but maybe make it very light for a start?
i did that
would help if you could provide more context
I am making a vr rocket league type game were you use your hands instead of a car and I am having trouble making the ball because when I hit the ball it doesn't go very far
reduce drag and mass
did that
and did it make a change?
not really
you could make a code solution by detecting relative velocity and applying a much larger force, but i think this is just a physics setup issue tbh
I fixed it
Hello! Could you help me please with SO and link to scene objects?
I know by default it's not supported, but I found out in Unity doc about ExposedReference and it looks like it what I want.
I've found few videos but can't make sence of how it's actually works. And in Unity it's example with PlayableAsset that I'm not aware of https://docs.unity3d.com/2017.3/Documentation/ScriptReference/ExposedReference_1.html
May be someone have guide about it or some links?
any idea why an argumentexception only occurs when running a development build but not the editor nor the release build?
Depends on the error and it's context.
I did a technical interview test for a unity xr position, I failed the test but one of the areas I failed in was apparently Unity-specific optimizations. Here is my repo: https://github.com/Asriela/Test but in general I dont understand what they are referring to especially in such a small test.
you might want to direct people to something specific but just checking out a few random pieces, stuff like this stands out
https://github.com/Asriela/Test/blob/main/Assets/2/2.3/Scripts/RotateCube.cs adds garbage on coroutine creation + garbage every delay time. Why start a new coroutine every time instead of creating one in OnEnable? I also don't like the way you named _rotationSpeed because that would definitely confuse me on what this script does, and hardcoding initialDelayTime is also weird
https://github.com/Asriela/Test/blob/main/Assets/5/Scripts/Utilities/Singleton.cs implementation is incorrect
https://github.com/Asriela/Test/blob/main/Assets/5/Scripts/UI/UIController.cs transform.Find is terrible. Use of GetComponent afterwards is terrible
https://github.com/Asriela/Test/tree/main/Assets/5/Resources Did you make this folder? The contents make me think it should not exist
I can't speak to the XR-specific stuff
Thank you so much I deeply appreciate these insights. Arn't these general c# optimisations, why would they say unity specific optimisation techniques?
the things they listed above, coroutines and not using transform.Find is unity specific
I can speak to the VR stuff personally,
`Describe how to optimise Unity performance for XR applications. (10 points)
Reduce draw calls by combining meshes, minimizing dynamic objects, using gpu instancing so identical objects like billions of rocks can share
a single draw call.
optimize lighting by baking lights into the scene for objects that don't move so its once off, use light probes for dynamic objects
to seem lit up by baked lights and generally have less real time lighting.
Don't render each eye separately , thus halving the render work.
Optimize textures and materials by compressing textures which are thus quicker to load into memory and take up less space in memory,
mipmapping so that we switch between different resolutions of textures depending on how far away they are, combining textures into a single
atlas and don't do fancy shader stuff like complex fragment shaders.
LOD and culling, models become lower res when they are further away, thus having fewer polygons and don't render stuff that's outside the camera view.
Do physics calculations at a lower rate and don't use complex colliders like box or sphere.
Lower the resolution of each rendered frame or use foveated rendering, keeping the center of the frame high res and the peripheral areas lower
res where the player eye isn't really focused.
Don't go crazy with spatialized audio , its taxing. Also lets not get wild with the amount of active audio sources either.`
All of this is spot on, but you have the collider stuff backwards:
complex colliders are mesh colliders, but other colliders like box, sphere, etc, are the ones you want to use
I think unity's order of collision simplicity is sphere -> capsule -> box -> convex mesh collider -> mesh collider
Im trying to learn how to make ai, after about a hour of browsing, it seems like unity's navmesh only works on small maps/editor mode.
Im trying to make a ai for my 3d sandbox game with random terrain generation, do anybody know a video or just resources in general that could help me on this?
You're probably looking at either runtime navmesh generation or finding a different nav solution that can asynchronously bake navmesh at runtime.
Thank you, I definitely typed that wrong, I meant to say use simpler colliders like box or sphere.
I figured, you were 99% right so it was obvious to me it was a typo
However I didnt know that exact order so that insight still helps.
navmesh ai is going to be much easier then making an AI from scratch though, right?
or does it not have that much utilities
Unity’s nav mesh can be generated at runtime
IMO the newest navmesh package is really great. I can even use AI agents on physically driven platforms with it.
you can indeed generate at runtime
You just have to be smart about it and update a volume near the player/enemies
Guys I have a doubt. So I am making a 2d game. But now the main menu should have a zoom in effect and particles and other stuff while switching to other sections of the menu. Should I shift to world space ui or continue with screenspace canvas ui
Not a code question and do not cross post
Okay sorry
does anyone know what is the rendergraph equivalent to CommandBuffer.ClearRenderTarget? i'm just trying to clear the current camera buffer (including depth) up to that point.
solution: using cmd in an ExecutePass function with RasterGraphContext (there's also CoreUtils.ClearRenderTarget but i couldn't figure out how to pass the command buffer into it)
code 👍
Will splitting up the lines like this help me pinpoint which part of the line has a nullreferenceexception? Or will it always say the first line
yes it will help
Worth testing yourself and seeing, though splitting lines will give a different line number for the error, another approach can be using debug logs or breakpoints which could give you more info as well
you have 4 things which could be null there
well when I did it it was giving the first part of the line so I just wanted to know if it always did that or if it was saying that that was the part which had a nullreferenceexception
Ah yeah, then its likely the error is before the = sign
seems like maybe 3 to me
3 on the first line 1 on the second
ok thanks
NodePositions is a property of save.spriteShapes[ID]
save
spriteShapes
spriteShapes[x]
spline
spriteshapes is also a property of save
so what, it could be null
in this format
spriteShapes is a property of SaveData
save is of type SaveData, so it could either be an instance of SaveData or null
spriteShapes could also itself be null
or it could be holding nulls
why are you assigning empty arrays to them?
so I can set the lengths of them later without them being null
but not by using array.length
no, that's not how arrays work
I'm actually assigning them to a new array[length] later
yeah, so you're just assigning new arrays
why not just use null to indicate it hasn't been initialized
so you can actually check for that
does not assigning to it at all also do that
or a List, if you want to dynamically resize it
yes
null is 0, interpreted as a pointer/reference
just like false is 0 interpreted as a boolean or '\0' is 0 interpreted as a char
ok now I'm really confused. It's giving an error at line 674
I'm clearly defining save at the top
then why would it be giving me an error at line 674
that's where the expression is
so splitting the line doesn't give more precise information?
or does it treat the whole save.spriteShapes[x].NodePositions as one expression
well at least I know how to fix it now
...yeah, because that's what it is
oh I thought it would let me know which part was null
but I guess that's not how the compiler thinks of it
I think they will not follow the parent if WorldPositionStays = true
i dont think that's true. They will be child of that transform you parent them to, effectively placed in the localspace of the parent
Okay, let me try. I observed that behavior a while back, before fixing other glitches, but maybe falsely attributed it
Why doesn’t onapplicationquit work on android but works on ios
because Android does not actually close applications
Would onapplicationpause do a similar thing? Or in order to trigger onapplicationpause, do I need to open the game again?
yes
Yes that's what the docs recommend too:
"Warning: If the user suspends your application on a mobile platform, the operating system can quit the application to free up resources. In this case, depending on the operating system, Unity might be unable to call this method. On mobile platforms, it is best practice to not rely on this method to save the state of your application. Instead, consider every loss of application focus as the exit of the application and use MonoBehaviour.OnApplicationFocus to save any data. "
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html
pause and/or focus depending on what you want. The Unity docs cover all of this
Focus is a superset of pause right? Pause + notifications etc
Afternoon all. Having a really weird problem with Unity. I'm creating a player controller and for all intents and purposes it works great. I've double checked all the backing fields and they are reporting the correct values from input. Yet, when player has Direction.X of -1, the animation associated with Idle_Left is set to use the same sprite as Idle_Right, but using FlipX = true. Yet my character only faces 3 directions: Up, Right, and Down. If I go left, it just shows the idle anim for Right. I tried on Unity 6 & Unity 2021. I even dumped ALL of my code and rewrote the files from scratch and same issue. I've never seen this before, any ideas? I've thrown my code files into one central link: https://codefile.io/f/VJD6SjcNTn
Here are the animator & animation screenshots too
Solved. Adding Renderer.FlipX was creating an additional keyframe at the end of the single frame animation.
Hello all! I'm making a trash recycling game and I want to make a prefab that spawns random food models (like it could spawn a donut one time and the next a banana, something like that), how do I do that?
put the objects prefabs inside an array, get random item by generating a random index from 0 to yourarray.length , use instantiate to clone it.
eg
[SerializeField] GameObject[] myObjs
int randomIndex = Random.Range(0, myObjs.Length)
GameObject randomPrefab = myObjs[randomIndex]
var myRandomItem = Instantiate(randomPrefab, etc.```
btw this would be more for [#💻┃code-beginner](/guild/489222168727519232/channel/497874004401586176/)
Okay! I'll go resend the issue there
no need to crosspost
I mean I pretty much showed you an example of how you would do it..
I have 2 meshes that I generated through code. Is there a way to cut a hole out of the first mesh in the shape of the other mesh? (I want a "Mesh 2" shaped hole in "Mesh 1")
Yes, but why not just use blender for that?
They probably want some sort of Boolean effect at runtime I presume
Probably not that complicated. Just get all verts and remove the second mesh triangles
I'm guessing this is done by some marching cubes algorithm, but I do not know
Actually still have to figure out an alg like some closest neighbor to connect edges to those verts
Eh, now that I think about it, it's probably pretty damn complicated assuming we're talking about any mesh
Preferably you don't do any cutting and you fake it with shaders. It's an XY problem
yeah I'd just stencil a mask through it and call it a day
this would be of use to you https://discussions.unity.com/t/boolean-subtraction-operations-on-mesh/442402
I do not know if shaders would make real holes though (As I do not use them often), but cutting the mesh would, if you do not need real holes (e.g physics objects falling through them) you could probably fake it
Probuilder's runtime API might be interesting if you actually need to do these kind of operations
I'm trying to assign to a variable because it's null, but I'm getting a nullreferenceexception
Seems pretty clear that the element is null not the element's transform
Look at your own logs
because you're not assigning the element?
What do you mean?
the name is misleading
but I'm not trying to get the transform of the object
I just named the variable transform
Oooh
well that's confusing
because that shouldn't be null
I'm assigning to it before
I don't see where you're assigning the element
you're creating an array
but its elements will be null
Oh I guess they should be assigned here
but what would I assign to transform other than null
for (var i = 0; i < levelData.TerrainShapes.Length; i++)
levelData.TerrainShapes[i] = new();
Populate your array's elements so they are not null.
Imagine you want to create a shopping list. you grab a piece paper with 10 lines on it
time to go to the shops and get the 5th item on your list
but you never wrote the list so what's the 5th item, how do you buy it
Same thing here, you created an array with some space, you never wrote to it, and you tried to assign something to one of the non-existent elements
Alright everything is working properly now, thanks!
Im not sure if this is the place for it because its sort of a shader thing but I downloaded the project of a splatoon painting tutorial and was trying to read the paint mask with getpixelbilinear, but its always just grey. It works perfectly with the first texture, which is a random texture from the project that I made readable, but the generated mask texture does not work. Does anyone know why? I tried creating the same texture from scratch in the code as a render texture and assigning it as readable, but to do getpixelbilinear I have to convert to texture2d which seems to undo that setup and results in the second uploaded image. Im not sure what else to try, I have no idea why its not reading the texture correctly, its displaying correctly in the inspector
hey does anyone else have this bugged ui element for the new input system binding action menu
the "listen" and search button are overlapped with the drop down menus
i am on unity 2021.3.40f1
that was fixed in a patch later than the one you are on
Good evening everyone I had a quick question about character customization to make sure I'm on the right path. is this the right place to ask advice?
This is the place to ask advice on your code.
I am almost convinced that this is broken in unity. It is impossible to get the pixels on this texture in code despite it being right there in the inspector
Did you try debugging at different stages? Or stepping through the code?
Ive tried a ton of things, not sure what else I could do, the top code chunk turns the renderer into a viable texture2d thats visible in the inspector, but any attempt to actually get that texture2ds pixel colors results in grey. I dont know any other way to go about doing this
funnily enough, one of my friends is also stuck on this despite us working on our own projects
Debug at every step. Or step through the code with a debugger.
I havent used the debugger, no really sure how I would look for an error with it here, but of the billion things Ive tried, there was no inbetween, I can get a visible texture2d of what I need in the inspector but no attempt to read it will result in anything other than grey. I can get pixels of texture2ds from within the project no problem, but ones generated in the code cant be gotten, Ive gone through every parameter associated with textures, texture2ds, and rendertextures, they all check out, no combination of any kind would allow getpixel to work
For starters, you could debug the value you get with GetPixel. As well as make sure that the object(texture) that you're accessing is the one you think.
are you sure the data is actually being copied to the cpu? The next thing to check out is whether or not you meet the requirements for that to happen with CopyTexture
what do you mean meet the requirements of?
surely you read the doc for Graphics.CopyTexture? https://docs.unity3d.com/ScriptReference/Graphics.CopyTexture.html
Im assuming you mean this? yes, theyre both readable
if they werent I would get an error, I got one earlier when turning it off to see if it would do anything
and the format is compatible, and the size is compatible, and anti aliasing is correct, and your api supports it etc? https://docs.unity3d.com/ScriptReference/SystemInfo-copyTextureSupport.html
I think they should confirm what they're getting with GetPixel first, as I mentioned earlier. Perhaps the problem is not there at all.
yes to all
I have a mask texture thats like splatoon paint on a wall, the paint mask texture is created live during the game. I want to get that mask and use getpixel to determine if the raycast/cursor/whatever is currently over a paint spot or not.
I never asked for these details. I provided you several things to check, but you seem to ignore the suggestions.
Ive given you everything like 5 times dude, converting the rendertexture to texture2d with graphics.copytexture generates the image correctly atleast in the inspector, at which point any attempt to getpixel on it will provide a grey result unlike the texture2d visible in inspector. Kind of rich that youre saying Im ignoring your suggestions when youve basically not even specifically acknowledged anything Ive posted
You're still ignoring what I suggested here:
#archived-code-general message
https://discordapp.com/channels/489222168727519232/763495187787677697/1312651627101945936
second image literally shows the getpixel output
No, it does not. It shows the result after copying and applying it to the other texture. And even then it only shows what you see in the scene/inspector and at different point in time. It ** does not** show what GetPixel returns.
get pixel returns gray regardless, whether its applied per pixel or just gets the value of one pixel specifically is irrelevant, the output is grey. I dont know what specific debug menu you are trying to get me to go into but Ive already said that Ive debugged a ton of possible values like its mipmap, its readability, its format, etc.
There's no specific debug menu. You either use logs, like you did now, or attach the debugger and step through the code/use breakpoints.
The log indicates that it actually does get a non default color, which would imply that it works. Now, whether that color matches what you're expecting or not (and why) is a different question.
I have debug crawled through the output texture before and the entire thing is that color, its totally grey. thats why Im commenting, I swear Ive done everything and nothing has gotten it to not be this specifically. If the value changed atleast itd be something but its been this the entire time
that's the color you get for an uninitialized texture on my system
Right. The next thing to check is the other thing that I mentioned: that it's the correct texture. You can pass a second parameter to Debug.Log such that the passed object would be selected/highlighted in the editor, when you click the log message.
Its accessing the right variable but its refusing to highlight it. I can replace the variable with an image from the project through and it works. I tried to see if there was some execution order error but it doesnt seem like it. I tried to only grab the mask once so it couldnt get overwritten to see if that was responsible but that didnt work either. nothing is working with it, this all works insanely easily with textures in the assets but it just refuses to work with these generated maps. Ive tried to find where or if somewhere in the code specifically destroys the masks after theyre applied but I cannot find anything. I might just have to copy the theory behind the project and write it myself from scratch so I can assure that the mask textures are accessible at all times.
If it doesn't highlight the texture you expect it to be, then perhaps it's not it. Try debugging the instance id from GetInstanceID of the texture that you're confirming and compare to the instance id in the inspector. Should be able to see it with debug mode inspector.
if you're generating the texture, is it being saved/stored correctly (since regular textures from assets folder work)?
I closed the project but reopened it to try this and now the painting doesnt even work anymore despite me not touching it at all. So I guess I give up. I'll just throw planes everywhere with textures and raycast to see if I hit those, whatever. I heavily regret trying to learn game development, what a total waste of time. Should have stuck to blender
You can't really make a game in blender(even though it had a sort of game engine at some point?). If you don't need a game, then perhaps blender would be better indeed.
Lastly, we don't really know what you're trying to achieve and why you decided to implement it like that, but usually, you'd rely a lot more on shaders and graphics api if you need to copy textures around. It's not very practical to copy a texture on the CPU side. Perhaps if you did it the proper way, you wouldn't have so many problems.
Hi. What are the differences between the different "GraphicsBuffer.Target" please? Like, what's the difference between GraphicsBuffer.Target.Structured and GraphicsBuffer.Target.CopyDestination for example? And does it affect performance a lot or...?
Hi if I want to draw gizmos and handle in-editor code when a particular monobehaviour is selected what is the best option? Using OnDrawGizmos in the actual monobehaviour and making it editor only code is a bit cludgy, can I have a separate editor monobehaviour that detects what is selected and draws gizmos when a certain item is active?
I think I need to use Handles instead...
VS is totally broken for me writing editor scripts currently - the fade out unused code bug, all editor code classes are red underlined 
yeah after this latest mess Rider should be the answer - but waiting for its AI line completion equivalent
what is JetBrains AI like? Does it work with Unity code?
It seems like they abstracted the graphics buffer type and/or state with this Target property. The exact implementation would depend on the graphics pipeline.
In d3d11/12, it probably creates the corresponding views for the buffer and creates it with the corresponding flags.
If you don't specify the correct targets, you wouldn't be able to use the buffer correctly (and even if you do, the graphics API would probably throw warnings at you and tell you to fix it).
ultimately, if you don't fix them it might lead to performance degradation or even crashes, depending on the hardware.
oh okay, thanks. So if I don't get any warnings I'm all good for now if I understood correctly
Probably. Some warnings/errors would only be thrown when the Graphics Debug Layer is enabled, and I'm not sure how unity handles it.
But yeah, just make sure that you're using the buffer only for the purposes of the targets that you passed into the constructor.
vscode also works 🙃
Hey, just curious. Is there any variant of something like spherecast or capsule cast that only counts a hit when its entire volume is obscured instead of if any of it is obscured?
A cast gives you a buffer of all candidates that could satisfy this property. You can filter that buffer yourself with additional checks.
_rigidbody.position = movingPivot;
_rigidbody.constraints = RigidbodyConstraints.FreezePosition;```
if i do this, my object isnt teleporting to the position but gets its poisition freezed, even if the .position is first
Likely rigidbody position is only applied in the next physics frame at which point it is set to be frozen
thanks, didnt think about that
Is there any reason performance wise to have the collect logic on the pickups themselves using the observer pattern or just have the player/collector process said logic, more specifically something like the OnTriggerEnter Method
Like if you made mario would you have the coins detect the trigger and raise the collection event or would you give mario a collector class and have no scripts running on the coins besided animation or something, are there performance reasons to do or not to do either
That's actually a good question for something I've been meaning to look into more, but most tutorials will usually just have that logic on the pickup item itself. If there's some performance implications of doing it this way, then I do not know, but it is much cleaner to manage as if I want to know the behavior of these objects I can click on them right in the scene.
Logically if you have 1 player and 1,000 coins then having the code on the player will be more performant than having it on all of the coins. So it's a matter of your design
As long as you're using callbacks instead of update or something, it won't really make a difference.
Is there any way in the code to make audio play instantly when being ran by the code, im making a plane game about just staying in the air as long as possible, Each highscore value has it's own biome and music. All of the songs are made specifically for each biome however they are all just different versions of the main game songs meaning it would be great to have the Audio play instantly after being ran by the code instead of having a 0.5-1.5 second delay.
The way i do it is simple
{
}
else
{
// Check the biome level etc etc, then trigger that biome's void which has an GameMusicSource.Play(); in it.
}
However like said, there is a 0.5-1.5s delay between the audio stopping and the next one playing, it would be extremely nice to have it play instantly without any delay so it's a smooth transition
make sure you aren't calling AudioSource.Play multiple times on the same object. and also make sure that there is no extra silence at the beginning of the track to ensure it does start playing immediately
There is no extra silence at the beginning, also i am using the same AudioSource for each level, just changing the Clip of it. So if i use different AudioSources it will be smoother, is that what you mean by saying, to not use the same object.
no, using the same audio source is fine. i'm saying to make sure you aren't calling Play on it a whole bunch of times because that restarts the audio each time you do, which means it will appear to be not playing
Oh, no im not. I just call it once each time the biome changes since it's in a simple void. Each time the Audio ends the if detects the biome and then calls the method with the AudioSource in it. And thats where i cant figure out the problem, either it's by defualt like this in unity and there has to be some pause, or im just doing something wrong.
None of the audios have any silence at the beginning.
Is there a delay at the track end? Because if you're gonna wait for it to end, obviously nothing is gonna be playing in the meantime.
No, all of them are made by me and i've especially made sure that there are no empty spaces to keep them smooth.
then you'll likely need to show more context 🤷♂️
Try adding logs to see when the previous clip ends and a new one starts.
And whether it's matching what you're hearing.
Is there any way to make a script entirely read and not write so only the script itself can access and change variables inside of it? (e.g A Global script which gives and updates variables for all scripts)
private fields, public readonly properties.
oh sweet, I didn't know readonly existed thanks man
oh you don't need it, you can just make them getter-only
readonly on the fields would make the script not able to modify its own values
pretty sure readonly is invalid on properties
oh, yeah I want the script itself to modify its own variables
I'll look into getter-only, thanks
you can do public int X => x; for a public readonly property backed by x
oh right, you could also use an automatically-implemented property with a public getter and a private setter, that's another option
Yup this option works wonders, a private setter and public getter worked, many thanks 😁
Hi! I have quite general question about lists.
I do create enemies that I add to list for tracking.
Then I do remove them from lists from time to time based on events (destroyed or not visible anymore).
The issue is - if I iterate through list and something removed from it, I'm getting error (since it's C# behaviour).
Is there good approach to handle such cases? I can recreate list as "cached" and iterate through it, so even if object removed from "main" list, I still won't get error. But I feel it's not good approach either.
What error are you getting? I am going to make an assumption that you are using foreach? If so, yeah that is not great. You should use a for loop, and even better a reverse for loop, then it shouldn't be an issue.
I don't remember exact error (can't reproduce it as of now), I believe it's some sort of concurrent modification or smth like this (when we change list when it's iterated).
Could you clarify please how reverse loops is better than usual? I technically can remove item form beginning or from the end or in the middle. Or add item.
oh.. if I add item it will be missing in current iteration but will be ok for next, and if I remove, count will be lower, but since I iterate backwards I wont get an issue. right?
Iterating backwards will avoid index issues and be more marginally performant from my understanding.
But the real issue is using for instead of foreach
Yep, I understand now.
Is it possible to get en error when I get index and start iterating, but then righ away item removed from list? So for example I had 10 items, 1 get removed but I'm on 10th index trying to get item
yep. you right
but is it possible before it handles 9 idex, number of item will change to 9
The index changes between iterations. You know, i--
Is that what you mean with number of item
nope
Okay, not-unity example (since I'm not sure how unity handles it)
We have two threads.
In one thread we iterate through list. We assume list have 1 to 10 items. Therefore index will be from 0 to 9.
In another thread we reduce number of items one by one.
it's totaly possible that while we not started iterating our number of items in list will change.
And when we will try to get item by index 9, there won't be 10th item.
Thats called a race condition and should be avoided
I got question about ml-agents here. Does anyone know what could be the reason both of my Continuous Actions and Discrete Actions alway output the same number no metter how I train it?
public override void OnActionReceived(ActionBuffers actions)
{
Debug.Log("Move X:" + actions.ContinuousActions[0]);
Debug.Log("Move Y:" +actions.ContinuousActions[1]);
Debug.Log("Rotate:" + actions.ContinuousActions[2]);
if (!moveLock)
{
controller.HorizontalMovement(actions.ContinuousActions[0], actions.ContinuousActions[1]);
}
controller.HorizontalRotation(actions.ContinuousActions[2]);
//Jump
Debug.Log("jumpAction:" + actions.DiscreteActions[0]);
int jumpAction = actions.DiscreteActions[0];
if (jumpAction == 0&& !jumpLock)
{
if (controller.JumpAction())
{
AddReward(-0.1f);
}
}
Debug.Log("LeftHandAttack:" + actions.DiscreteActions[1]);
//Left Hand Attack
int LHandAction = actions.DiscreteActions[1];
if (LHandAction==0)
{
controller.LeftHandAttack();
}
Debug.Log("RightHandAttack:" + actions.DiscreteActions[2]);
//Right Hand Attack
int RHandAction = actions.DiscreteActions[2];
if (RHandAction == 0)
{
controller.RightHandAttack();
}
Debug.Log(".Sprint:" + actions.DiscreteActions[3]);
//.Sprint
int dashAction = actions.DiscreteActions[3];
if (dashAction == 0 &&!dashLock)
{
controller.SprintAction();
}
}
Does anyone know what I can use as an equivalent to vector3.rotatetowards with either quaternions or float3s
quaternions fly completely over my head is there some way to like... clamp Quaternion.FromToRotation with the specified angle change I want?
I'm not sure what you mean by "float3". I'm used to seeing that shader languages like HLSL and GSL to represent a Vector3. So if you have a Vector3 representing the direction toward which you'd like to rotate, then rotateTowards should work. If you want to do it with Quaternions, then I'm guessing the answer to your question probably involves Lerping between two Quaternions, but I'd like to know more about the expected behavior.
unity.math.float3
maybe what you want is to slerp from your current rotation towards the target rotation? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.Slerp.html
slerp unfortunately will not work
I don't want to modulate between the two rotations by a ratio if that makes sense
I want it to move x radians / s
like rotatetowards does
what's the problem with rotatetowards, then?
im in ecs
you're supposed to use unity.math
aka float3s the new vector3s
and there is unfortunately no float3.rotatetowards
(I think you can't burst mathf)
oh I see, I haven't messed with that. you probably have to do some quaternion*vector math or do a bit of trig
so that would kind of defeat the purpose of me using ecs in this scenario anyway
I think quaternion.axisAngle does what you're talking about.
yeah
looks perfect
thanks
well, I still need to somehow clamp so it doesn't move past where it needs to look but
definitely a start
guess i just find whatever is smallest the axisangle or quaternion between 2 quaternions
actually thats quite easy
Im not sure if this is related with code but it probably is
my nav mesh agent is behaving very wierdly, it seems to pause and only continue its process upon triggering a input.key method or switching to another screen.
I have a function which pauses its pathfinding in a corutine. (IEnumerator)
I dont think anyone can help without seeing your code
ah
I was wondering if it was a niche thing with unity unrelated with code
private void OnTriggerEnter(Collider other)
{
if (other.transform == player) // Ensure it's the player colliding
{
// Apply knockback force
Vector3 knockbackDirection = (transform.position - player.position).normalized; // Direction away from player
m_Agent.isStopped = true;
m_Rigidbody.isKinematic = false;
m_Rigidbody.linearVelocity = knockbackDirection * knockbackForce;
// Temporarily disable movement for the knockback duration
StartCoroutine(ApplyKnockback());
}
}
private IEnumerator ApplyKnockback()
{
isKnockedBack = true;
while (m_Rigidbody.linearVelocity.magnitude > 3f) // Continue until velocity is less than 1
{
m_Rigidbody.linearVelocity *= 1-knockbackRes;
m_Agent.velocity = Vector3.zero;
m_Agent.destination = transform.position;
yield return null; // Wait for the next frame
}
// Re-enable NavMeshAgent to continue movement towards the player
m_Agent.isStopped = false;
isKnockedBack = false;
m_Rigidbody.isKinematic = true;
}
So your character has both a rigidbody (that is not kinematic) and a navmesh agent?
I'm pretty sure that combo doesn't work
They will both be trying to control your movement
the rigidbody is normally kinematic
its only set to non-kinematic when the knockback process is in place
Yeah I shoulda read more carefully lol
However, the problem may very well be the IEnumerator not ending correctly
such that the isKinematic is not set back and the m_agent still being stopped
though i dont know why it is in relation with... switching into another screen.
Why is my line renderer have to stretch so far (eg: -34 units) to cross a gap that in reality is only 2 units apart?
your scale is obviously not what you think it is
Right, I looked into it and was using worldspace, but now let me start from the beginning, since this problem as been beating me up:
I want to make a line between 2 points, these points are children of 2 main objects, like so:
Drill - CableTerminalA
Storage - CableTerminalB
I've tried everything so far, positions just keep eluding me and im not sure what to do.
so what is the problem with
positions = new Vector3[2];
positions[0] = CableTerminalA.transform.position;
positions[1] = CableTerminalB.transform.position;
I might need to rethink this, as its a bit messy and complex at the moment, will let you know if I manage to get it working
yep, was way overcomplicating it, thank you steve
try using the quaternion.eulerAngles
oh wait what do you mean by float3s?
I mostly work in 2d but I don't get why a vector3 wouldn't be fine
That's what Quaternion.RotateTowards is for
it took me litteraly 20 minutes to realise its vertical and not horizontal 😭
Hello! Me and my friend are collaborating through GitHub and she can't open the scripts I made and neither do the ones she does work. What can we do?
read the warning there and do what it says?
So a combination of WorldPositionStays = true + setting their rigidbody interpolations to none upon being stacked, fixed my issue completely. Thanks guys for helping & motivating me @timber rampart @heady iris
There aren't any errors on the scripts
I can work with them, but she can't do anything
and what does her console show?
irrelevant if there are no errors on your machine, there could be other problems stopping the compiling
and what is selected (where) to show this inspector? Something from the scene? or the project window?
From the project window
She's either got compile errors, or not pulled the project fully.. or something. She needs to come in here and get help, it's a waste of time going through a third party
If disabling interpolation fixed it, then you should try directly setting the rigidbody's position and rotation. That should allow you to leave interpolation on.
Just tell it about its new position + rotation at the same time that you mess with the transform
I'm getting IOException: Sharing violation on path on this. What does that mean?
I think unlike WriteAllText CreateTexts opens the file and you have to manually dispose it with using statements so its keeping the file open and writealltext can't write to same open file
do I even have to create a new file if it doesn't exist?
WriteAllText cretes one for you
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-8.0
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is truncated and overwritten.
Oh ok I'll remove the creation line then
ya try that out. it might just fix the issue
you really should use Path.Combine rather than building path strings
What’s that do?
sorry I was in the car while making that message
You also don't need to check if the directory exists before creating it. CreateDirectory() does nothing if it already exists
im trying to make multipalyer with photon and i need to put "if (view.IsMine)" some where so that the players dont meve each other does anyone know where to place this
@fluid parcel
or anyone
thanks
I have a project, based on a grid of cubes, that change state - whether you can walk through them or not, Occasionally I am able to walk through a cube that visually seems as though I should not be able to walk through.
Grid manager: https://pastebin.com/F8MbU4mf
Player movement: https://pastebin.com/VkeTRcB1
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.
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.
So added lives to my game and every time u die u get 1 life off with a picture of a pingiun getting of the screen. I made a game data but the lives go down it but the pictures always go back to 3 even when i restart
great, and you are posting in a code channel why?
bcs i need help with my code
then may be share 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.
thats unityengine not unity.math
like i said... because vector3s aren't burstable
nvm i found how to do it
Burst…?
that was fast lol
Burst is a compiler that you can use with Unity's job system to create code that enhances and improves your application's performance. It translates your code from IL/.NET bytecode to optimized native CPU code that uses the LLVM compiler.
https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/index.html
Would I need to provide anything else to get any help with this issue?
https://hastebin.com/share/vojimigaji.csharp
Why do the pics of my lives not reset when i restart my lives?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Oh cool so like a super optimized type of compiler
pretty much
Restart where?
190 and 195
currentLives = maxLives;?
my max lives are set to 3
and when i completly die i set my currentlives to max lives
where do you reset the gui though
might wanna do thaat lol
or is there documatetion link?
set all the colors in a loop to alpha 1 or 100%
personally i would enable disable UI elements inside a layout group
Not sure if it's the best way but you could do this:
- Find the angle (in radians) between the two quaternions with https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.math.angle.html
- Figure out what percentage of that angle your desired amount of rotation is. For example 50 degrees is 50% of 100. (don't forget it's in radians)
- Use https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.math.slerp.html#Unity_Mathematics_math_slerp_Unity_Mathematics_quaternion_Unity_Mathematics_quaternion_System_Single_ to create the new quaternion based on the percentage you calculated
what is the color code for not transparent?
look at what ur doing in the code to make it transparent lol just do the opposite
color in unity goes 0-1
your code is only ever setting the alpha to 0
yeah that could work thanks
compute shaderable as well
Btw this:
public void UpdateGui()
{
if (currentLives <= 2)
{
Color tempColor = Pinguin3.color;
tempColor.a = 0f; // Set alpha to 0 (fully transparent)
Pinguin3.color = tempColor;
}
if (currentLives <= 1)
{
Color tempColor = Pinguin2.color;
tempColor.a = 0f; // Set alpha to 0 (fully transparent)
Pinguin2.color = tempColor;
}
if (currentLives == 0)
{
Color tempColor = Pinguin1.color;
tempColor.a = 0f; // Set alpha to 0 (fully transparent)
}
}
}
Is not really sustainable. You should get used to using arrays and loops instead of naming variables with numbers like this. It's going to be a nightmare to maintain this.
Color tempColor = Pinguin3.color;
tempColor.a = 1f; // Set alpha to 0 (fully transparent)
Pinguin3.color = tempColor;
Color tempColor = Pinguin2.color;
tempColor.a = 1f; // Set alpha to 0 (fully transparent)
Pinguin2.color = tempColor;
Color tempColor = Pinguin1.color;
tempColor.a = 1f; // Set alpha to 0 (fully transparent)
Pinguin1.color = tempColor;
Especially because now you need to write the code that sets things back to 1 alpha or whatever
so just like this?
Yeah see how you're writing another 16 lines of code or whjatever
Use a loop and an array
// Set alpha to 0 (fully transparent)
That's not right
fix the comments
i just copied
god forbid your player could ever get a 4th heart container
the comments need to be removed
suddenly all your code needs to be rewritten
This is an excellent opportunity to learn about loops and arrays or lists
never learned a array at school in c# only in phyton
arrays are pretty much similiar across the board
usually something that holds more than 1 value. like a collection
they are similar to python lists
lists in c# are just arrays that can be resized
wait so why have I been using arrays for so long
arrays are more efficient if you don't need to resize them
the amount of times I've had to make a new array with the new length I want then iterate over the old list into the new one then assign the new variables
How do you even define a list
also do they work with foreach
thats basically what list is doing
oh wait that's a google question
they work the same way as array except you can add/remove elements.
oh gosh yes you should be using lists for that
Not sure if I want to go back over all my old arrays to see which ones could be rewritten as lists
but I'll definitely keep it in mind
I mean you could use an array for this anyway
also can't you just do penguin.color.a = 1f why do you need a temp variable
you cannot
It's a funny intersection of two things
Coloris a struct. You hold onto aColordirectly, just like anintor afloatSpriteRenderer.coloris a property. It looks like a field, but it actually calls a method that returns the color
Modifying the returned value would do nothing. It's not the same Color that the sprite renderer has.
I prefer to use extension functions in this style: https://github.com/jschiff/unity-extensions/blob/338d306ba17f86efa7beea1618ef486132e42720/Runtime/Extensions/VectorExtensions.cs#L49
So then I can write: penguin.color = penguin.color.WithA(0);
I mean i'd just make penguin a separate class and do it in a color property
unless this game is like a 2 hour project kind of thing
Well I think in this case, it's a UnityEngine.UI.Image
but yeah even a helper function would go a long way here.
yeah but i mean i assume the game isn't literally just about a picture of a penguin that does nothing but change colour
What generally could be affecting script compile times
This U 6.0.25f1 project is fairly barebones and it seems like script compilation takes either 3 seconds or 60 and nothing in between regardless of the change
There is a package that shows all of the assemblies that are getting compiled
You could look at the editor logs and see if there's anything really funny in there
I just installed unity again after some time and my visual studio is graying out the unity functions because it thinks they are unused. how do I turn that off?
I bet Visual Studio is missing its Unity-specific features
so it doesn't understand that Unity messages exist
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
if the function works, then it is the VS bug going around thinking everything is unused
VS in particular has been doing this for people recently
I do not know how long it has been going for
People been saying you need the .net desktop platform development kit for some reason
I just installed unity and visual studio code again after like a year so I wouldn't know. The unity functions do work, the editor just thinks they are unused.
yup its just the VS bug then, I don't know how to get rid of it 🤷♂️
there is a related bug in some of the newer visual studio versions
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025
im making a game where you drive a car on a road, i want the game to stop if the car is even slightly off the road so is there a way to script a polygon collider around my road??
how are you making the road
splines
Use the spline to generate the collider then as well
i just learned how to make a road out of splines
how do i do that exactly?
Sample the spline every n units, and offset according to the spline's tangent and rotation to get the points for the collider
I'm curious about this. What happens to overlapping points?
Here's what I mean
That's up to you.
it depends on what the desired gameplay is
But that's a nice illustration of what I meant by using the spline to generate the points, thanks
I ask because I recently made a "path gun". The geometry of my mesh would get very weird in thos places. I didn't really know how to tackle the issue
I think most likely it's fine to just ignore the fact they overlap. The collider will do the right thing anyway
But it depends on the specifics of the game
That's good to know. So it's only a problem when drawing a mesh
If you mouse over the word Random in your Random.Range line what type is it referring to?
It should say if it's e.g. UnityEngine.Random or something else.
I.e. see here it's telling me it's a class in UnityEngine
so at least the using statement works
ah that fixed the issue
i dunno why i did that
oh right regular C# random was what was in my mind when i tried to use unity random
yup that one you def new() an instance
Ah yeah... the other screenshot conveniently omitted that haha
The error message was a bit confusing though...
There is no Init function on GameObject
What is the type of the _fruitObject variable?
I made the init function in the game objects class
no you didn't
that's not a GameObject
that's some custom component you wrote
What is the type of the _fruitObject variable
the monobehavior i put on the prefab?
Fruit which is the name of the script I put on a prefab
Please answer this question.
Instantiate returns the same type that you pass into it
so you have Fruit _fruitObject; somewhere?
yes
ok so
that should be fine then
Are you getting an error or something?
What's the issue?
Again though, you would be calling the method on the component, not on the GameObject here
i just never called the SpawnFruit function
Is there a way to just mark parts of a nav mesh as unwalkable?
ofcourse
Cheers, pursuing that now
you could potentially also use navmesh obstacle
in the inspector view for a Quaternion, why cant i set the x rotation above 90 nor below 270? and when x is 90, why cant i set z at all? the property is just a simple public Quaternion rotation with nothing on the script running while in the editor
then why is it just fine when modifying it on a Transform?
Eulers
If you can't modify it in the inspector that's usually a sign you have some OnValidate code or something overweriting it
The inspector for a Quaternion shows euler angles
Right, the transform in the inspector is done in eulers, right? Cause I run into gimble with that
i dont have any OnValidates defined in any of my scripts
Or an ExecuteInEditMode e.g.
neither that
Those are the only reasons I can think of.
Show code?
If you make a new field does that new field work ok?
Also are you using any plugins/packages
its on any Quaternion everywhere
Sounds like probably a plugin or something..