#archived-code-general
1 messages Β· Page 23 of 1
if the camera is a child of the player, try rotating the player first
The camera follows the player, it's not a child
void LateUpdate()
{
if (isFirstPerson)
{
currentOffset = Vector3.Lerp(currentOffset, firstPersonOffset, smoothSpeed);
}
else
{
currentOffset = Vector3.Lerp(currentOffset, thirdPersonOffset, smoothSpeed);
target.rotation = Quaternion.Euler(transform.rotation.x + thirdPersonXRotationAngle, transform.rotation.y, transform.rotation.z);
}
transform.position = target.position + currentOffset;
}
Got this second script on the container of the camera
So you are already moving the camera by code. Then you need to add logic there that it orbits the player.
related more to coding, when the lady keeps saying we are "loading" in the Firewatch open world video, does she just mean setting objects active / inactive?
I would calculate the ideal camera position in player transform space, and then lerp the camera there
Can I make prefab Variants from/of prefab variants?
the details depend on what type of third person camera motion you want, either free or constrained to the direction of movement in some way
Well there are a bunch of tutorials on orbiting camera's.
There is also the premade Unity 3D person camera controller.
Can you not use either of those?
Well I wanted to discorver it not taking something already done. I should recheck some tuto thought
Okay that's fair, learning is never bad. You could implement Pavel's idea then, that's a good start.
I'll start with that thanks !
while executing the task wont go further than first Log, no exceptions or anything
accessing unity obejcts from threads other than the main thread results in your thread unceremoniously dying
with no log/error/etc
in this case - calling GetComponent is your crime.
Debug.Log($"Message received: {e.Data}");
var resp = ServerStatusResponse.CreateFromJSON(e.Data);
Debug.Log($"[{resp.packetType}] [{resp.body.status}]");
if(resp.body.status == "OK"){
Debug.Log(resp.packetType);
Debug.Log(resp.body.status);
} else {
Debug.Log("Failed to check");
await ShowFailText();
}
};
how should I implement this feature then, I've found out that coroutines do not work either in event calls
what is ws?
WebSocket from WebSocketSharp
Signal the main thread from here
and have the main thread show the error message
Easily done if using UniTask for example, or easily hacked together with a ConcurrentQueue
if I use UniTask and call its methods from event call it will handle everything for me in main thread?
as long as you don't use threading in the main thread
unity is not thread safe, so you can't make any calls to the unity api from threads other than the main thread
UniTask has a "switch to main thread" thing
I don't remember what it's called exactly
await UniTask.SwitchToMainThread(); thx, I'll try
yeah that thing
Not sure if this is the right area or not, if not please point me to it.
I have a menu prefab that holds some scripts, well Iβm carrying through scenes using DontDestroyOnLoad except with it being a menu prefab it has to be enabled at all times in the inspector or the other scripts in the new scene trying to use it canβt reference to it. Is there a way for me to SetActive vs SetActive to false and still be able to reference it to?
The simple solution I can think of is to just make another script that I can attach to the objects in the new scene that just calls functions from the prefab.
(I may also be wording this poorly) please let me know. Thanks
Just reference it via a static Instance field
rather than using FindWithTag or whatever you're doing
that works perfectly, thx a lot
How do I get a Quaternion rotation that is pointing in the direction of a vector?
Quaternion.LookRotation(myVector)
Great! Thanks
Assuming myVector is a direction vector and not a position vector
Yep
how can I rotate a gameobject along its axis
which axis
z
and do you mean around an axis?
{
Ship.transform.position += Vector3.right * 10 * Time.deltaTime;
float tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle;
float tiltAroundX = Input.GetAxis("Vertical") * tiltAngle;
Quaternion target = Quaternion.Euler(tiltAroundZ, 0, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
}```
yea
I have that, it nearly works though
ahhh
what are you trying to achieve here
when I press A, rotate the gameobject left a lil
How would I enter a variable that with a type of "Type" (confusing π ) here?
{
if (itemType.IsSubclassOf(typeof(ItemFramework)) && !itemType.IsAbstract)
{
go.AddComponent<typeof(itemType)>();
}
else throw new Exception("Given Type is not a subclass of ItemFramework or is abstract.");
}```
Specific code snippet:
```go.AddComponent<typeof(itemType)>();```
Don't cross-post
Use the overload of AddComponent that takes in a Type as a parameter
Why isn't this working
can you show me? (sorry for cross posting btw)
go.AddComponent(itemType)
oh you can just do that?
thanks!
yep works, again thanks!
bcuz v2 is not a float
Vector2.Distance gives back a float, you're trying to put it in a variable of type Vector2
the resultof v2 distance is float
ooh yep
my bad, thank you
Can someone explain me pls why 11 line is not working. I chose necessary layer in script and set the same layer for gameObject.
A layer mask is not a layer. Layer masks are like collections of layers. You need to check whether the object's layer is included in that mask
Ok so I have this piece of code that I want to calculate a direction and a force based on the distance of an arrow that the player chooses and I want the distance to determine the magnitude of the force but I'm pretty sure I shouldn't be multiplying by distance here...
Vector2 direction = (mousePos - (Vector2)transform.position).normalized;
float distance = Vector2.Distance(planet.transform.position, mousePos);
Vector2 setVelocity = direction * distance;
planet.GetComponent<CelestialBody>().initialVelocity = setVelocity;
Visualization
Like OverlapCirce? And i cant Convert layerMask to int to compare?
You'll have to do some bit-level operations to check that. Something along these lines
if (((1 << coll.gameObject.layer) & layerMask) != 0)
{
// In mask
}
Seems complex at first, let me know if you need an explanation on how it works
Basically I need to rotate the rotation around the blue arrow until the green arrow is straight up. I have no idea how though.
Ah. Okay. Thx
Anyone?
Divide by distance
Afterwards multiply by a speed parameter
Not sure I understand your question
Why should I divide by distance?
Basically the player can control the length of the arrow above
It's like a planet right?
and the length determines how much the planet will be launched by
Oh I see. Then multiply
No problem there
If mousePos is in world coordinates of course
You may want an extra multiplication factor (or even a curve to evaluate against) if you want to have more control over how the distance affects the velocity. It depends on what you want the relationship between distance and launch velocity to be.
the problem is the force isn't noticeable
Afterwards multiply by a speed factor
A float value
For anyone wondering, I have fixed my problem with modifying skinned mesh in runtime. In order to avoid changes to source asset you have to do this Mesh projectMesh = _skinnedMeshRenderer.sharedMesh; meshInstance = new Mesh(); meshInstance = Instantiate(projectMesh); _skinnedMeshRenderer.sharedMesh = meshInstance;
Can you send a screenshot of the complete script?
Nice. This is actually pretty useful
Alright gimme a sec
We have 5 "shared servers" lol
PlanetSpawner: https://pastebin.com/aPdUB0eT
CelestialObject: https://pastebin.com/8azQzxEa
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.
Alright let me take a look
I think there is an issue with the celestial body script cuz the initial velocity in the inspector is appearing but it's not getting applied
Probably
You never call UpdateVelocity()
or UpdatePosition
Oh yeah that's being called in a different script dw
Are you sure that UpdateVelocity() and UpdatePosition() are being called?
Try making them serialize fields
Alrighty I fixed it
What was the issue?
{
currentVelocity = initialVelocity;
}
I just call this function from my planetspawner script
and it sets the velocity
Yup, except there is some wonkiness with the direction when the arrow is too close idk what's up with that
I'll send a video
acc nvm my pc is dying rn
Ahah ok
How do I make sure that the red red arrow is always pointing strictly to the side while the blue arrow still faces the blue sphere? I am assuming that this is what causes the whole flying off into space bug
Currently I am using Quaternion.LookDirection(blueSpherePos - yellowSpherePos)
I will just use a workaround instead I think
how do I rotate a lowercase q quaternion 90 degrees in one x y or z direction?
This shouldn't take close to 2 hours lol: https://old.reddit.com/r/Unity3D/comments/10kdzqw/need_to_rotate_by_a_fixed_amount_using_a/
0 votes and 5 comments so far on Reddit
okay off to my job at the scientific research lab, Thanks everyone ahead of time for thinking of trying to answer.
This is what I was talking about
For some reason the direction works half of the time
what's a "lowercase q quaternion"
Yeah for some reason they don't let you do
var result = quaternion * quaternion
(Multiplying quaternions is how you add them)
So you have to use var result = math.mult(quaternion, quaternion)
well yeah Unity.Mathematics is modeled after HLSL
so it's mul(q1, q2)
which is how you do it in hlsl
Which is stupid imo.
mult(q,q)
q.mult(q)
q * q
Are all functionally equivalent. Back then it was a case of language restrictions and optimization. That isn't the issue today
They wanted to make it comfortable for shader programmers to use
They still should allow both options
Β―_(γ)_/Β―
But I am glad they added swivel support
Damn that looks good. Not sure I can help though, sry
Alrighty, thanks anyways
My guess is that you aren't properly setting your initial movement vector.
Since directionVec = pos_final - pos_initial I bet you are using the wrong position. Like maybe your previously created object? That or you are making your movement vector based on some local rotation
Hmm I'd have to look into this after I go back, that actually might be the issue
Or maybe some wrong rotation vector math?
Heavens know I've messed up way too much vector math in unity
This is still the script btw
I don't touch rotation though
Oh didn't see the script. Lemme check
I would recommend using more variables for clarity.
Like:
//after mouseclick
var finalPosition= ...;
Anyways I think line 89 looks wrong. I don't know why you are taking transform.position, since that's the position of the script object
π€¦ββοΈ π€¦ββοΈ π€¦ββοΈ
I have done this exact single mistake 3 times now
Good variables names help
Yup, I'm always tryna improve my code but apparantly I didnt do that hear
Just takes practice. I've made the same mistake too many times myself
To be more specific, I like to define the names of all the variables I think I'll need at the start (even if I don't how how to calculate their value) and then work with setting them
Oh yup, for me sometimes I don't even know what those are so I'm still working stuff out lol
Anyways thanks a lot!
Hey! I want to learn how to build a chunk system but i dont know how it does work in unity - so my thoughts about that were that every time the player moves into a new chunk there will be a foreach() loop and forech chunk which is not in a certain distance to the player it will be setActive = false -> my question now is: is this how you do it or is there a more performant way of chunk loading because if there are like 10000 chunk objects i think it could be very inperformant - thanks for your replies
basically just keep track of the currently loaded chunk.
Every time you step into a new chunk you:
- loop over all currently loaded chunks and unload any that are two far away
- load any that should be loaded but are not currently loaded based on the new chunk position (a set intersection works here)
there's no reason at all to loop over 10000 things
also SetActive is not really the relevant thing. Your chunks should not be in the scene at all until you get close enough
Can someone tell me why this is happening? Its always when its pointed to the right and has positive angle velocity, i am rotating it with rb.AddTorque()
first of all thank you but there is one thing i do not understand at this point: if i just loop over all the chunks that are loaded i cant load the chunks that were already generated and store data or am i wrong?
you are wrong
you can store generated chunks however you wish - as long as it's not in memory
throw them in a file
or a database
or whatever
ok ill try it with a file - thanks
the logic is basically:
- Try to load chunk X/Y
- see if there exists pregenerated data for the chunk
- if so, load it from file or whatever
- if not, generate it now
- see if there exists pregenerated data for the chunk
Player slows down when facing down
because you are moving based on the camera's transform.forward rather than the player body's transform.forward so you are smashing your player into the ground since your camera is pointing at the ground as opposed to moving forward
also you need to configure your IDE because there is a suspicious lack of highlighting for unity types and methods
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio: https://on.unity.com/vshub (Installed via Unity Hub)
β’ Visual Studio: https://on.unity.com/vsmanually (Installed manually)
β’ VS Code* https://on.unity.com/vscode
β’ JetBrains Rider: https://on.unity.com/3XgkeqG
β’ Other/None: https://on.unity.com/3CYp2c9
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
tried doing what, moving based on the player's transform.forward instead of the camera's? because that will work provided you didn't do something silly like make the player a child of the camera
someone has a wacky coding issue in #π§°βui-toolkit that someone should go check out maybe
I've got no clue why it isn't working
Ahh, no I meant the IDE stuff. But it worked when I look down the player moves but it also doesnt actually go the way its meant to. XD
that's because you aren't rotating the player around the Y axis, you're only rotating your camera
Can anyone point me in the direction of some tutorials or info on blend shapes in unity? But not with faces, I am trying to have a sphere morph into different shapes. The sphere and the shapes will come from 3ds max models
Daily reminder to not be dumb and put repeating coroutines into start and not update π
So what happened to this FPS sample, it seems like a great resource but looks abandoned?
https://github.com/Unity-Technologies/FPSSample
Any chance to get unity employees to look at the PR's? Or is there a replacement maybe?
"Update about the state of the project: This project is based on Unity 2018.3 and no longer being actively maintained." from your link
Unity has a lot of projects, and is always working on something, when they release newer versions of unity, there are lots of changes that would need to be made to all previous projects to keep them up to date.
Does anybody know a easy way to implement air strafing?
Just do normal strafing, but don't limit it to when you're grounded ?
Found the FPSSample very interesting because of the included netcode, anyone have a recommendation where to find something similar that is... Easier to compile and run?
Does anyone know how to make a fane object appear to fade away, I feel like you'd use its alpha value but I don't know how to code it to decrease it gradually
Thankyou very much
i've got a question regarding AotHelper, i'm trying to write a system that will basically enforce AoT compilation of types that i try to deserialize so that way we don't need some convention solution in order to hack around it
// Relevant code portion
string json;// has some value
List<Foo> deserializedList = JsonConvert.DeserializeObject<List<Foo>>(json);
// this would cause the Aot compiler to strip List<string> unless it's specified elsewhere
AotHelper.EnsureType<List<string>>();
AotHelper.EnsureList<Foo>();
// Would these achieve the same goal, or would not using EnsureList be a problem?
i know ensurelist does multiple ensures under the hood, that's not the question though
for them to have different code they have to be different scripts
is that really your question? how can i have two things with different code?
Why can I change Name in the inspector but not code?
If you're trying to change it in GlassPistol, you need to write the code inside a method
Thanks!
anyone got experience with a* algorithm?
Hey, working on a 2D metroidvania
I want to make some collectible coins that are physics enabled, that get sucked towards the player when they are close enough.
I can think of a couple ways to do this, such as doing a circle raycast to check if the player is in range, but doing that on every spawned coin seems inefficient/potentially lag inducing... is there a cleaner way to do this?
I have a Class with a List<ObjectModel> , is there any way to reference an existing model via the Unity editor? I only see an option to Add a new element and then I have to fill it out by hand.
i havent asked my question yet though
thanks for referencing a website that i have no use for
yes, that's the point
maybe if you actually read it you would see why i linked it
do the physics query from the player instead
bro
stop being an asshole
fuck off
anyway
Basically the Scriptable object with a list<Gems>. But the editor UI only lets me add a new element to list and edit the values manually. Is there a way to reference existing scriptable objects rather than assemble new ones in the editor interface for the list?
the problem is by asking if anyone is familiar with a*, you are asking someone to engage and commit to answering your question before even knowing what it is. Just ask your question, if someone is familiar with a* AND has an answer to your question, they will answer
adding me to friends to potentially get an answer from me is exactly the thing you should NOT do
the irony about them getting pissy about being told to just ask the question instead of asking for someone familiar with a* is that i actually am familiar with it lmao
i misclicked on the block button
if youre struggling with physics objects i dont need to
lmao me too, I use it for a few enemies in my game
now hes assuming my skill based on a question i asked π
I know a few ways to do what I asked, I'm asking how to optimize it to be efficient
I am admittedly not super familiar with the capabilities of unity's built in physics because I dont use it for much, I wrote my own simple physics for player and enemy movement
You'd want to use a collider and get an "OnEnter" check to activate the attraction movement.
oh yea, thats how to collect the object, thats no issue though
oh wait, you're suggesting using a collider in place of a circleCast I see
yea, that'd probably work
on enter, trigger some change in the physics that causes it to attract to my players hitbox
Yes, so, you could have one collider and just check vector diff (distance) to see if it's close enough yet to pickup, otherwise move a bit closer to player.
honestly i'd just overlapcircle from the player so the player detects the objects and applies any force to them rather than relying on collision/trigger messages
something like that.
that sounds more efficient
I'll give that a try
thanks
make that its own component and you can enable/disable the behaviour as needed too
that makes it easy to adjust the suction range too
I'm using A* for finding the most efficient path between two points. I have a situation where the G cost causes it to be inefficient (needing 10 to 20x more checks than setting the G cost to 0). In the image the red square is the start and the green square is the goal. As visible in the picture the F cost is now unnecessarily high. The code is all functioning as per the algorithm, using euclidean distance for G cost and manhattan for H cost.
Yep that works too. Then you can change the distance of the attraction globally too if you want equipment to be able to increase attraction distance for instance.
yupyup, thats the plan
equipable charms that affect stuff like that
Wait can I not make a wrapper of MonoBehavior? Like have a class inherit a class that inherits MonoBehavior?
I know for a fact I have done that in the past, but currently I am getting an error when trying this.
Wait nevermind, I had a class below the MonoBehavior class in the same file.
OOOOh, you opened up a door, Lord Kelvin would have loved to have available to him. Kelvin (inventor of the scientific K scale of temperature) once said,""Quaternions came from Hamilton after his really good work had been done; and, though beautifully ingenious, have been an unmixed evil to those who have touched them in any way, including Clerk Maxwell."
Every time I think of a quaternion, I just pretend its a Vector3 value with a Vector3.up value stapled on
yah, there's something I saw a video where it's the vector3,aimed in a direction...
But I looove the snark in old scientists... Hamilton made em after he did his good stuff, like they're rock stars terrible sequel album
And makes a dig at Maxwell's Equations,lol.
YUP! I put the code in, tots works.
Sometimes I think mathematicians live in their own little world...
One of planar geometry and quadratics
Wizards of Snark
See we all go to school to learn how to do math.
G is supposed to be real cost of the known half of the path. H, which is the heuristic, needs to be less then the real cost of the remaining path.
But only a Mathemetician can PROVE 1+1 =2
If math is so complicated, why is it only built on top of like 2 assumptions?
we start by defining the set of all things that are not equivalent to themselves, the empty set: β
Hi guys, I have two videos here. The first video, which you should start watching at 15 seconds, shows the movement I'm trying to make for each character. The second video, which you should start at 17 seconds, shows the movement I've created so far.
The movement I created assigns a direction for each instantiated character to move in, when instead I want to make all of the characters that are from the same prefab move in the same direction. Any ideas on how to do this?
The movement in the second video is choppy because I'm recording, it's not normally choppy.
Here's the code for the movement: https://gdl.space/apaxolujof.cpp
I am using unity fps microgame. No matter if I enable/disable invert y axis, it is still inverted. I do not know why. Even if I remove the invert code completely, it is still inverted. Any ideas?
float i = isGamepad ? Input.GetAxis(stickInputName) : Input.GetAxisRaw(mouseInputName);
// handle inverting vertical input
if (InvertYAxis)
i *= -1f;
my guess would be your code is ignoring this i value completely
or you are not properly enabling/disabling InvertYAxis
hi , does anyone knows what that error means ?
just what it says
access static things with the class/type name
not an instance reference
you are doing:
someParticularCat.Meow(); when you should be doing Cat.Meow();
@leaden ice Thanks :D, I tried few things and I think I could just make the delegate public instead of static, Im still testing but If it didnt work I'll use ur advice π
sounds like you're overcomplicating whatever you're doing but ok
I have a ParallelForTransform job that simply make a transform follow another transform
But it seems to be lagging behind for some reason (Especially 2nd, and 3rd follower)
I'm not sure what went wrong
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.
It only happened for like a frame
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
If I had two script components, is it always the case that their Awake methods would be called before their Start methods? Like
A Awake -> B Awake -> A Start -> B Start
Whichever comes first between A and B doesn't really matter, since I'm aware there's no set order between component executionβwhat matters more for my assumed use-case is that Awakes are all batched together
Assuming they are created/spawned at the same time, sure
In reality though all Awakes are not batched together
you will get e.g.:
A Awake A OnEnable B Awake B OnEnable
all of this will happen long before any Starts are run though
Yep, they're attached to a player prefab that's inserted onto the scene
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.
chunk loading code
how can I make it better?
I need advice On how to proceed With CreateAssetWhenReady
I want to be able to call the constructor and have the values populated via the function inside.
but I get errors saying I am running the function while unity is Updating.
How would I Run the CreateConnectedAsset function when that finishes (arguments included)
https://pastebin.com/xTRcFBAJ
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.
i literally just came across this issue. StatTracker needs to grab a Stat from CharacterStats but StatTracker runs its initialized methods (Awake, OnEnable, etc.) before CharacterStats. i thought, at least the CharacterStats Awake would run before StatTracker Awake, but no . . .
this is why Start exists
if your script depents on the initialization of another script, you should run that dependent code on Start. Start runs after every script in the scene completes their calls to Awake()
yeah, but this was using Awake and OnEnable. i didn't think it's (ONEnable) run right after Awake since it deals with the activation of the game object . . .
And some guy said that the ones in the same grey box can switch in order sometimes.
^
essentially treat OnEnable the same as Awake unless you're manually toggling the gameobjects
or if you're doing event registration because you want to unsubscribe on onDisable
really the only time you can be absolutely sure that one object's Awake and/or OnEnable has run before another object's is when you Instantiate them in code because Awake and OnEnable are both called immediately upon instantiation
I know, i had the code in OnEnable since it runs after Awake. figured all Awake messages would run before OnEnabled was triggered, not that they'd run concurrently with each other . . .
never had an issue with it until that moment . . .
they run arbitrarily. i believe the initialization code runs through scripts in execution order, calls awake, which enables the game object and triggers onenable
it's not like everything runs awake -> everything run onenable
not to beat a dead horse but that really is exactly why start exists
to guarantee initialization
I also didn't know the ones in the same grey box could switch, but it was one of the smart people here that said that, so I assumed it was true.
self initialization in Awake, initialization of anything that relies on other objects in Start
yeah i just think of Awake like initialization and start as linking
yeah, i know, but it depended on activation OnEnable/OnDisable, not a one time boot like Start . . .
then you have what we call highly coupled code
and you should probably refactor it to not need to do that
but you could always set a flag in start and if onenable is called before the flag then it no-ops, but then you'd have to do whatever you wanted to do in onenable ALSO in start
and it's just gross
no need, was just playing around and testing out a certain mechanic/architecture at 5am. just thought it was interesting since i never came across the issue when using OnEnable . . .
what is the specific issue
so you have a stat script and a stat TRACKER script?
i feel you tho. i'm just curious
What's the appropriate way to rotate an object with a CharacterController component?
tryna figure out how to explain it with this setup. prolly easier from the gun/turret i just finished playing around with
there's no issue, it was moreso testing. i was just thinking of different ways to build and architect a system or mechanic, test it, and see if it could work. the idea was making stats for an object; instead of placing them as a field on a script, like Player, Enemy, etc., i made a separate script for them. then i wondered about referencing those stats to use in other systems and mechanics. StatTracker<T> is a test to track a Stat for use in a base mechanic
i'm creating β yet another β HealthSystem to see if i like how it's setup. e.g., a Heal mechanic or a Damage mechanic would derive from StatTracker or StatTracker<T> and are fields referenced in the HealthSystem. The Heal mechanic will have a HealthService module(s), a ScriptableObject that you can drag n' drop to change how the heal(ing) occurs. the same applies to the Damage mechanic along with its DamageService module(s)
i was debating if the mechanics should be coupled with health system or not and if i wanted them to update the value of their Stat when and if the object is disable or enabled . . .
Hi, lets think i have 5 gameobject attached same script and in this script i have a static int which is someIndex. If i call MyScript.someIndex how do i know which one is it? or because of it is static theres only one someIndex?
Im not really good with statics and im currently working on it and i have this question
static means it is owned by the class rather than the instance. so each instance of that script would share the same value for that static variable because that's literally what static does
its actually one someIndex i guess then?
the entire purpose of static is that it is not tied to any instance
a static field belongs to the class, not the instance. it will be the same value when any instance accesses it . . .
okay got it thanks
Any statics (class, variable) initialize when program loads? before everything like awake- start?
thanks
thats true right?
static members are initialized before you access them, yes
thanks a lot
Anyone have a suggestion for how I could determine whether a collision is occurring "inside" an edge collider (orange) vs. occurring "outside" an edge collider (blue)? I first thought of checking the dot to the collision normal, but the normals of an edge collider orient in both directions (green)
if you get the hit point, should that not return a vector to determine in which direction it is looking?
That's the problem, with an edge collider, the collider appears to have normals that point in either direction (green lines in the pic above), so whilst I can determine the direction, it doesn't help me understand whether they're on one side of the edge or the other.
the collider might have normals in both, but what about hit.point.normal ? That could at least tell you if its looking towards the center of the edge collider or not. But that is highly risky if your edge just is not setup to be always convex
You could also check the points the edge has been created of and see, if the next point is to the left or to the right. In those cases to the left would be outside and to the right would be inside.
Hmm, this sounds encouraging! I'll poke around in this direction, as per your prior suggestion, I can't guarantee all shapes will be convex. Thanks!
so... is this a bug or something? What am I missing?
public void OnBeforeSerialize()
{
if (rotation == new Quaternion(0f, 0f, 0f, 0f))
{
Debug.Log("why won't it get here?");
rotation = Quaternion.identity;
}
Debug.Log(rotation);
}
You can't compare quaternions directly
https://docs.unity3d.com/ScriptReference/Quaternion.Angle.html and check that it's smaller than a small number
how small of a number would you suggest?
like a little bit above float.epsilon small?
besides, I want to check if it's EXACTLY 0 anyways, because I'm getting an error that the quaternion is invalid because all its elements are set to 0 when I create an item in a list, which is very annoying, and that is what I'm trying to solve.
then check if x, y, z and w are all 0
Hello, looking for a way to get data from light or how much light is hitting a certain mesh material ? ( like a sphere.)
Need a way to determine if sphere is in the shadows or not.
would much appreciate any suggestions on this matter
Quaternion.identity is 0, 0, 0, 1 isn't it? A Quaternion doesn't allow all 4 values to be 0 afaik, it always points somewhere. You could check the eulerAngles if those are all 0.
So in Test Framework 2.0.1 we can use Build Configs for playmode tests in a build. I'm wondering if there is any way to trigger this via command line? I checked the docs but there's nothing there. I feel like it would be strange if the only available option was to go via the Unity GUI...? When testing otherwise is fine through commandline with -runTests.
My guess is that this does not work because you're comparing references, and Quaternion has no build in comparison that ensures you actually compare its values
Hence why you should get something that you can compare with, such as the angle
Also comparing floats is never a good idea with == as decimals can be all over the place. You might just have a threshold and use a vector comparison to see, if the rotation is pointing in the same direction as your other vector
Yup there's a reason why there's a pin for that in #π»βcode-beginner
Do CharacterControllers not collide flush with other objects?
Elaborate?
Your hitboxes are wonky
That isn't the CharacterControllers fault
You can adjust the hitboxes
They are not, good sir
Proof?
And the hitbox of the plane?
Of the plane
Mmm the plane's collider isnt really obvious from a screenshot like this
Anyway, same problem occurs if its any object
Do you know if character controllers are supposed to move flush with objects? Even if the Move I am providing it would send it further than where it should stop?
It's not supposed to float, no
Try with a new plane?
Assuming it's a plane
Tis all colliders it cannot approach
controller.collisionFlags == CollisionFlags.Below
This however resolves to true when on ground
Is it a problem?
For my game? yes
In general? Yes. Especially if it isn't supposed to function this way
Lmk if anyone knows what the issue is here
Good morning everyone! Just joined in, I've been developing a videogame for the past two months, but yesterday I found myself struggling on something I think it's quite stupid.
I have a mini puzzle game (something like the Operation board game, you have to drag an object without touching a labyrinth collider) inserted in a 2D sidescroll exploration level. For reasons regarding the labyrinth collider, I couldn't code this in UI, cause I couldn't find a way to give the correct collider to the labyrinth image, I suppose because collision in UI are not handled in the same way as the scene.
So I made a scene object with the images needed for the Labyrinth to be played. It has the correct collider and I spawn a small object cursor on top that the player can click and drag across the puzzle game.
In the background I have a Tilemap with the background tiles (I'm using the preview package Tilemap 2D extras for autotiling).
So at this point comes the issue: the Tilemap Collider attached to the grid in the background, prevents me from clicking on the object cursor and start the drag function, like they were on the same layer of collision. I don't really understand how is that possible. The grid is on a certain sorting and collision layer, the puzzle game is on different ones. I also set up the collision Matrix to prevent the two chosen layers to collide with each other (I did it both on 2D and 3D collision matrix even if I'm working only in 2D, I'm desperate!) but the grid still prevents me from clicking the object on top.
I don't have the project in my hands right now, but I can post some images later, if it helps.
Thanks a lot and sorry if this breaks the rules in any way! In that case, tell me straight away and I'll reformat the request in a proper way.
How do you register clicking in your code?
With IDragHandler interfaces
Drag, BeginDrag and EndDrag
if I deactivate the grid, the whole thing works! So i know it's that collider interfering
Crappy way to do it is disabling the top collider whenever you do the Drag thing
do you mean to disable the Tilemap collider while I'm playing the puzzle?
The one that's preventing you from interacting what is below it
Maybe you can just disable it as a raycast target though https://gamedev.stackexchange.com/questions/167602/tell-unity-to-use-a-certain-layermask-to-raise-or-not-ondrop-for-a-class-that-i
That's the problem, the grid collider is BELOW the puzzle object
this might help! thanks
I'll have a look
Yeah so if you disable the TOP whilst dragging there'd be no issue
Though that'd still be a scuffed way of doing it so I'd just look into stuff like this
Yeah, should be able to send out a raycast from the mouse into the screen and have a look at exactly what the cast colliders with. Can go from there
that will defo help me debug, Don't know I didnt think about it before
There must be some stupid stuff going on with the raycast, thanks guys!
Have a crack and absolutely come back and ask more stuff if needed(:
already loving this server
I mean you constructed your question very well so then you also get good responses :p
Not often people do it the right way right away kek
Quick question, can you use deltaTime in async calls? I barely touch async voids most of the time so I am wondering how to wait for a value like in a coroutine.
public async void AnimateScale(RectTransform rectTransform, AnimationCurve3D animationCurve, float duration, int delay)
{
Debug.Log("Startanimation");
rectTransform.localScale = Vector3.zero;
await Task.Delay(delay * 1000);
Debug.Log("Delayed");
float timeElapsed = 0;
while (timeElapsed < duration && rectTransform)
{
timeElapsed += Time.deltaTime;
}
}
Can't you just test it?
Yeah it is not working like skipping the while part, googling in parallel why that might be the case
I see
I guess I have to use await Task.Yield();
I'd not know, a Coroutine is usually a nice solution
There we go, await Task.Yield(); is the equivalent to good ol yield return null; inside coroutine π
Ah
hi, how would you get the vector3 from transform.lookat without actually using transform.lookat?
What
like
transform.lookat changes the rotation
but how would you get that rotation without actually using lookat
if i'm not being clear i'll elaborate
Why do you want it?
it's for directional subtitles
i've been making the object use lookat but that kinda messes with the rotation of the gameobject itself so i've been wondering if it's possible
thanks!
Hey guys, I have an issue with Addressable Bundles and it's driving me nuts π₯
I have an addressable folder containing 2000 images for one of my scenes. But it's included (sometimes multiple times) in builds for my other scenes (which do not use these images anywhere)
How do I stop it from including all my adressables? I started using these instead of the resource folder for this reason π₯Ή Please help π
Sounds like an #π¦βaddressables question with all the addressable's in the question π
sorry didn't see that thread! thanks!
Hello guys, so I have this piece of code that zooms the camera according to if I scroll forwards or backwards but it's always centered, how do I make it so that it follows the position of my mouse?
{
if (Input.mouseScrollDelta.y < 0f)
{
cam.orthographicSize += 0.1f * sensitivity;
}
else if (Input.mouseScrollDelta.y > 0f)
{
cam.orthographicSize -= 0.1f * sensitivity;
}
cam.orthographicSize = Mathf.Clamp(cam.orthographicSize, 1f, 100f);
GameManager.orthoSize = cam.orthographicSize;
}
doesn't seem to be very active over there haha rip
You want it to orbit around the player?
Yeah, that's true, coding channels are very active compared to the fringe channels. But addressable's are something you need to have played with to be able to give an answer, and I for one never used them in 12 years.
No, I have a solar system that I can zoom in on
I can see why ^^' they are confusing. maybe I should rephrase my question haha, I have 2000 images I need to load. What's the most efficent way to do that? Resouces.load would be nice but then its in every scene (and of course I don't want that)
drag and dropping the 2000 images in an array in the inspector could be the trick but I don't remember why I switched to a different way of doing it haha so any suggestions?
so you want it to stay on a plane over the solar system but move along the plane?
No, I'll implement the orbiting later, wait I'll send a video to show what I mean
Here. It always zooms in the center and not the direction of my cursor
I'm gonna implement following and panning later on too
yupp
π€
You could use the magnitude of the vector from the center of your screen to where your pointer is on the screen (world to screen point) and use this vector to translate your camera in this direction ?
so you essentially zoom but also translate the camera some amount (you'll have to tweak this amount to make it feel good) in that direction
hmm that could work
so if center v1=0,0
your mouse is v2=-0.5,0.5 (mid top left) your angle would be v2-v1 (and here don't normalize the vector if you want to use the mag of this result as your amount to move the cam)
ooh ok don't normalize it
Reading the addressable documentation, it should exactly fix what you are trying to do.
I also don't know which of the 2000 you want to load? Are they based on language like you show in #π¦βaddressables? If so you can only Resources.Load that specific language directory.
well you can if you want but then your camera will move at the same amount (* some coef) no mater how far from the center your mouse is
But it's a problem i have never needed to solve, so maybe other people can help you better.
so it should feel a bit better to keep this not-normalize
not the locales are from the localization package and are handled seperatly (my game is in 4 languages) the only addressable asset I created is that "pangea" folder which contains 2000 images of the evolution of the earth accross 300,000 thousand years
so I have a slider (with 2000 points) that shows the image like pangea[slider.value] basically
I could load them as needed but I'm not sure how to do this and I think it would feel janky if the user moves the slider super quick
so what I did is I have a small loading before they get to play around with it that loads those 2000 images in memory and then ofc it's smooth as butter
so addressable seemed perfect for this. but for some reason they appear in all my builds no matter whether the scene loads them or not as a bundle and it's 700MB π’
so essentially they work just like the resource folder, only I have an extra loading screen haha which is terrible...
Thanks @main shuttle for the help though, google has been rubbish
Did you use the analyze tool?
https://docs.unity3d.com/Packages/com.unity.addressables@1.1/manual/AddressableAssetsAnalyze.html
As far as I read, you still have references in your builds to the addressables, otherwise it wouldn't load it in a build, with this tool you can see how/what. But this is all far away from my knowledge.
so I moved them to a group of it's own and un-ticked "include in build" which works and effectly stops including it in all my builds (already good) but then I have to tick it again for the one scene I want it for. Seems a little odd to have to do this, I really feel like I'm using this all wrong
I'll check it out
Yeah I clicked the "fix all rules", not sure what it did or why I would have to manually click such a hidden thing haha but let's see if it changed anything. It doesn't seem to show what asset is used where yet
I'll keep you in the loop!
thanks for the help
How do I make this smoother?
void Pan()
{
Vector2 mousePos = Input.mousePosition;
print(mousePos);
if (mousePos.y >= Screen.height * percentageOfBoundry/100f)
{
transform.Translate(Vector3.up * Time.deltaTime * panSpeed, Space.World);
}else if(mousePos.x >= Screen.width * percentageOfBoundry / 100f)
{
transform.Translate(Vector3.right * Time.deltaTime * panSpeed, Space.World);
}
else if (mousePos.y <= Screen.height * (100f-percentageOfBoundry)/100f)
{
transform.Translate(Vector3.down * Time.deltaTime * panSpeed, Space.World);
}
else if (mousePos.x <= Screen.width * (100f - percentageOfBoundry) / 100f)
{
transform.Translate(Vector3.left * Time.deltaTime * panSpeed, Space.World);
}
}
As in lerp it somehow
Anyone?
Where do I add cs
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hello! I'm building a json object using json linq. I need to serialize a list (made of a custom struct that has two strings). Does anyone knows how to do it?
Obv this doesn't work since "properties" is a List<Property> type and it's not possible to convert it
Note good possibility you're handling the others incorrectly too
No, they work
nice, it seems to work!
how do I parse that back to a list?
Just with ToString()
Why are you building a JObject when you can serialize/dezerialise the data into a class?
JObject/JArray/JToken types are usually used if you don't know what you get, or the data varies. This does not look like it
short answer: because I need it
Back to a list? You don't. That's not what JObject is for
You need a JArray by the way, to work with a list. Json only has 1 collection type
JObject is the final destination
Fair enough
I used jsonUtility for most of my projects, but now I need to use a more "free" json solution
??
to convert data directly into a class
JsonUtility is terrible, don't use it. Stick to Newtonsoft or anything else basically
And this, if you only use it to avoid JsonUtility, then JsonConvert will also just work
no, I use it because I need to build a json object without knowing its variables
Then it's fine, but getting variables from an interface is usually pretty static when it comes to what you get
that's my solution to have a saving solution not linked to a dataclass per object
If you mean that a variable might be null, then know that Newtonsoft can serialize that fine, unlike JsonUtility, so that's not a reason to use JObject
I'm building a survival, so tons of objects needs to be created
That's not something you use JObject for
e.g. with my solution I don't need a TreeData class, I don't need a RockData, FlowerData, CraftingTableData etc, I just need to implement "ISaveable" interface and everything works
You create a list for that
a list of saveable objects, yes
But those are all the same types
You can use a list of a set type there, not a JObject or JArray???
"set type"?
Also, you can serialize/deserialize your interface if you make it a class
Another reason why JObject is overcomplication
You can do this with JsonConvert. You just need to configure the serializer to write and read type info.
if I make it a class I need to make one per object
this whole setup is the only solution that's working that I thought of, and nor google nor this discord helped me when I asked what was the best solution
Maybe I'm confused on what exactly you're doing
look:
I would love to fix it for you π
These look like settings nvm I'm dumb
"savedObject" is the list of all the JObjects, a.k.a. one JObject per object
But every instance has the same set of data in them
you got transforms there (p*/r*s* is position, rotation and scale), and the ID
So you can make a class/record and specify the properties in there to deserialize in
Not?
I made an interface
You can't deserialize in an interface
WAIIIT
ahahahah
lemme explain
this is the grass objects
it has no custom properties apart from the basic one
you add that to every object spawned in a scene and the object is saved and loaded, forever
wanna add a custom variable?
public class saveObject
{
[JsonProperty("px")]
public float positionX { get; set; }
// put the rest here
}
Your class would be this, and you then have a list var @list = new List<saveObject>()?
do something like this (hits in this case represent the times a rock has been "mined", hit by the pickaxe)
Alright but you basically have a save system you need supporting
and this would work for a single object
what if I have trees, rocks, grass, the player, enemies etc.?
Hi, how can I reference some βglobalβ parameters between scenes (without using playerprefs or gameobjects with dontdestroyonload)? I thought about static classes but I dont know how to do it. I tried with something like this but it doesnt work:
public static class Parameters
{
public static int gamemode;
} ```
and then from another class
``` Parameters.gamemode = 1; ```
and you have custom vbariables for every one of them? like, a dropped item has to contain the ID of the dropped item, the tree has to know how much it has grown and when it was planted, a bush if it has berries in it etc.
solution if you convert a whole class: you can't, you need to create a class per object
What's the error?
OR, you create a JObject per object and load it with every variable that you need, base case is transform only, but you can add every other variable that you want
Unity just stops working. Is that code correct?
I get why you use a JObject then. Can I suggest you create a dictionary for any custom settings?
If Unity just stops working then you've a different problem
So you would have the saveObject I mentioned, with a "custom properties" dictionary
why? isn't that working correctly?
So your unity just crashes or?
where should I add it? I'm not sure I'm understanding what you mean
savedObject is a list
like that
it's only used when you need to save/load a chunk
you just run through all the savedObjects and load the savedObjectFinalList with that
yess
but the interface has this:
you have to implement the Save method
so for example that-s the save method of a tree
.
Unity stops, I wait and it stays the same, I need to go to task manager and close it from there
like that
do you have a while loop somewhere?
As in you cannot interact with anything anymore?
Check this then
ok, that was the problem thank you. I had a coroutine with a while inside without yield return null.
Hello. Was wondering if someone could help me. Have an issue where my bullet object isn't destroying my enemy object. The enemy is the trigger, and I'm using OnTriggerEnter2D(Collider2D other), which is working because when I don't have any extra parameters, the enemies are destroyed when they spawn in because they touch the ground. But when I use CompareTag to reference the bullet tag on the bullet object, it doesn't work. Any idea why this is? I'll gladly send screenshots of my inspector if needed.
jsonObject["properties"] = JToken.FromObject(properties); <- like that? (properties is a list)
Do the latter please
whenever you experience a crash, 99% of the time it's a while loop . . .
JArray.Parse
Well you need a JArray to begin with
have the bullet check the object it hit in its own trigger method instead of the other way around . . .
Wait, I think I found the issue. Might be an issue with the sorting layers in the Sprite Renderer
So you convert to an JArray if that's not the case (idk what you work with), and then use .ToObject<>
Nevermind, that was not the issue. Will send screenshots in a sec
like that?
What is jsondata?
it's my JObject saved object
I don't remember how to change a JToken to a JArray, but you can try this
literally one of the "savedObjects" of the screen that I sent before
in this case, due to the id, it's 100% a dropped item (so it's a JObject of a dropped item class)
But you can also just convert a JArray to a List<Property> without adding the loop
uh, any easy way to do it?
Both objects side by side.
And the code too please
{
private void OnTriggerEnter2D(Collider2D other)
{
if (gameObject.CompareTag("Bullet"))
{
Debug.Log("working");
// Destroy(gameObject);
}
}
}```
Do they need a rb to destroy one another?
at least one object in the collision must have a rigidbody component . . .
I recommend reading through this though
Added a rb 2d to both and its still not working for some reason
@thin aurora it doesn't work π¦
Because you're casting it to a string
If you can't use JArray.Parse with a JToken, and are forced to make it a string, casting it aint gonna work π
Try it
Show inspectors again
Also on which object is this script
Hi, im trying to save my settings menu across my scenes. Ive researched about PlayerPrefs, so im trying to use that. The slider just resets to 0 everytime. I have it so volumechange is whatever the slider value is (also updates some text from this). Then when you click Back, it should save "volume" as the volumechange value and in the start method (when the next scene loads up) it should theoretically set the slider value and text to the volume amount which was saved. This is not working.
On the zombie. Zombie needs to be trigger because it destroys the player ontriggerenter2d.
Isn't visible in the inspector screenshots
Hello,
Does anyone know how they usually program input commands in fighting games?
I tried to look for the source code for some games but the only ones I could find were for the really old games on ROM
Input.GetKey()
I just checked whether its actually saving it using PlayerPrefs.GetKey("volume") and its not actaully saving
The one it collides with isn't a trigger
And your code wants it to be
Also
!cs
I am not sure but in case this was an answer to my question, I don't think you understand the question
Define input commands
sorry, should have said motion inputs
Define motion inputs
do you know how hadouken in Street Fighter works?
How would I change my code to have the bullet (non-trigger) destroy the zombie (trigger)? Change other to collision?
is there another step im missing. Ive searched it up and cant see anything
β¬οΈ βοΈ β‘οΈ + PUNCH
Well you're checking for a trigger which the other isn't a trigger, but a collider, so yea, you want to check for OnColliderEnter2D
@leaden mural did you read this?
Wumpie, would you go with PlayerPrefs or a more complicated saving system. I cant seem to get PlayerPrefs working however i know how to get normal saving working.
Depends on the scope of the game
PlayerPrefs isn't hard to get working, but be mindful of typo's in strings
ive saved everything using files, however im trying to get PlayerPrefs working for saving my settings accross my scenes.
It just wont work though!
I've tried to build my own system around it but I've not yet to succeed with it, don't have the time for it
yeah same! My deadlines on friday for this college project ahaha
Oof
Maybe use this package so you can see what your PlayerPrefs are doing: https://github.com/Dysman/bgTools-playerPrefsEditor.git#upm
Im probably just gonna make a duplicate of my other save system
probs not optimised at all
that's a bite off the bigger topic of input buffering . . .
I did. OnCollisionEnter2D, but it keeps on saying the member is unused.
Code?
thanks, I will look into that
!cs
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
put cs on its own line . . .
public class KillZombie : MonoBehaviour
{
private void OnCollisionEnter2D(Collider2D col)
{
if (col.CompareTag("Bullet"))
{
Debug.Log("working");
// Destroy(gameObject);
}
}
}```
got it, thanks
You could've edited the previous one, but sure
you could've edited your previous message. just delete it now . . .
Does the text change?
Can you share the updated inspectors
When I ask for the inspectors I do mean the entire inspector. You can collapse unimportant fields like transform and sprite rendered in this case to make it fit
What collision type did you put the rigidbodies on
Fixed code to get rid of unused member error, but still the same issue.
Both are using discrete. Or did you mean the body type?
The latter, yes
Both are using dynamic
No. Would you like me to post the updated code?
Yes.
public class KillZombie : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.CompareTag("Bullet"))
{
Debug.Log("working");
// Destroy(gameObject);
}
}
}```
nope, but ive done it a less optimised way of a whole save and load system LOL
when I'm lerping EulerAngles, I get this thing where it jolts around when it goes from negative to positive, any fix?
i'd change the collider parameter name to collision so as not to confuse it with a Collider type since its actual type is Collision2D . . .
Im trying to find the magnitude offset/distance/angle of 2 rotations (quaternions) im saving, but it seems like Quaternion.Angle returns a wrong number even when the rotations are equal (per example for an Euler representation of, {0,0,0} and {0,0,0} it returns 180 (debugged to ensure the values)
How can i find the distance between 2 quaternions then?
or should i instead make a custom euler esque?
i know this is prone to gimbal lock, but sigh*
Hi everyone, I have this weird bug, not sure if it is caused by scripts on this project or something external. But as you may see the camera game object does not move with the transform component, may someone help me with this?
HOw do you see its not moving? I think I am blind π
Why do you think its not moving? The horizon is always the same.
Just add a cube in the scene, you will see that you are moving.
What is code related, there is no issue π
No clue what the actual problem is to be honest. That you don't fly into the clouds?
Yeah
What I'd expect is to get the camera move trough the clouds
They are C#/shader based clouds that use perlin/curl noise combined with a base texture in order to render them in-game
If its a shader, there is no 3D mesh at all, so how you expect to fly into a 3D world into a texture? If I get you right here
(not my work by the way, I've just been modifying it to work with planets and the specific unity editor version that I use)
As long as it is no custom volumetric cloud script, I guess, you just can not fly through it?
I agree with that, or it will look completely janky.
Thing is that it was working fine yesterday
On the same scene and camera?
Not the same scene
Well, you might be missing some settings you need to set so your camera gets the right information
You mean the event/function to ask if a path is valid and reachable?
nice talk tho π
In the end I had to re-import the settings, and now it works again
Thanks!
Hey I need some help please. The code for instantiating an item gives me an error although the code does execute.
https://gdl.space/zuyazubuna.cpp
But when I remove the 5 lines of code, no errors
question what's the order of the start functions being called for the scene? Is it topmost object all the way to the bottom most object? The reverse? All parents first then going down each child level in a similar sweep?
That is a very good question. I will have to double check that.
Click the error and give the stacktrace please
2 sec
Also, probably related, but please get rid of all the Find calls you have in the script. It's unreliable, a code smell, and most likely going to give you problems in the future
You should create a better way to get related transforms
ArgumentNullException: Value cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[TKey,TValue].FindEntry (TKey key) (at <d6232873609549b8a045fa15811a5bd3>:0)
System.Collections.Generic.Dictionary`2[TKey,TValue].ContainsKey (TKey key) (at <d6232873609549b8a045fa15811a5bd3>:0)
_1_Scripts.GameManagers.InventoryManager.Add (_1_Scripts.Utilities.ScriptableObjects.Item itemCollected) (at Assets/1_Scripts/GameManagers/InventoryManager.cs:43)
_1_Scripts.GameManagers.EventManager.RaiseOnItemPickup (_1_Scripts.Utilities.ScriptableObjects.Item item) (at Assets/1_Scripts/GameManagers/EventManager.cs:26)
_1_Scripts.General.ItemPickup.OnTriggerEnter (UnityEngine.Collider other) (at Assets/1_Scripts/General/ItemPickup.cs:17)
still learning but for sure. I'll refactor my code
well a key in a dict cant be null, that is what its saying.
sure but the key is not null if I remove the instantiation code. SO that is why I am confused
From what I see in your stacktrace, it is not talking about the script you gave us tho
what is Assets/1_Scripts/GameManagers/InventoryManager.cs:43) doing?
This error is in another file
ItemPickup, not ItemSlotActionHandlers which you gave
Correction, it's in InventoryManager
I am aware yes. however the issue I am trying to figure out why when I add
var itemPrefab = (itemScriptableObject as Item)?.itemPrefab;
var instantiatedItem = Instantiate(itemPrefab, GameObject.Find("Hand.R").transform, true);
instantiatedItem.transform.localPosition = Vector3.zero; //<--- Problem area
instantiatedItem.transform.localRotation = Quaternion.identity;
I get the issues of the dictionary value can not be null. I am just trying to add the prefab attached to the scriptable object to the world.
But the Inventory manager handles the adding and removing of scriptable objects and inventory item slots into the dictionary
I made a forum post about this, but I donβt think anyone had checked it yet https://forum.unity.com/threads/nullreferenceexception-object-reference-not-set-to-an-instance-of-an-object-error.1390179/
is Item a scriptable object?
correct
public abstract class Item : ScriptableObject
{
public string itemName;
public string itemDescription;
public Sprite itemIcon;
public ItemTag itemTag;
public GameObject itemPrefab;
public bool isStackable;
public bool isHoldable;
public enum ItemTag { TACTICAL, UTILITY,CONSUMABLE,THROWABLE };
}
}
Well the error you gave is most likely because itemCollected is null, in Add.
You should debug it.
I am not sure you can store a SO file in a dictionary. Just thinking loud here
It all works, just not instantiating the prefab
Which doesn't happen because itemCollected is null, in Add.
Hey I need some help please The code for
Guys why does the position where I spawn get offseted here?
I'm using cinemachine to implement the following but it gets offsetted somehow
Here is the camera script:
https://pastebin.com/ZXA3CNLi
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.
Please let me know if anyone can help
Also these are the two lines that instantiate the prefab:
GameObject planet = Instantiate(planetPrefab, spawnPos, Quaternion.identity);
This is literally the most common type of error you'll encounter
Reread it carefully
Alright
I noticed it only happens when I'm following the target
Acc now that I think about it this is expected behaviour
ScreenToWorldPoint does take in account your cameras plane settings, so the expected position might not be where you want it to be, cause the vector is shorter?
It's because I'm moving while I instantiated so the position is already set but I moved
There is no bug it's just normal behaviour
How can i pick a random point on the navmesh that i can move navmeshagent to (it would be nice if after the agent gets there he gets another point in a loop)
not sure if this is the correct place, but I get the following error:
What should I do?
Check the line its calling
public class HexGrid : MonoBehaviour {
private void createCell(int x, int z, int i) {
bool notFirstCellInARow = x > 0;
}
}
what is x?
function parameter
I do not think its a code error, does unity give any error?
no
wait wait I didn't provide full context
breakpoint doesn't work
π€¦π»
@plucky inlet
sorry
it just doesn't trigger
I'm trying to debug it
some array doesn't assign correctly
this happens
and I'm really outta options to solve it w/o debug
Just debug log everythign you can, my suggestion, otherwise it will just be guessing from my side
Hmmmm
I think it's something related to the new chunks system
I think the tiles aren't ordered correctly
ARRRRR
stupid debug no work
I have no idea where to start
I have no idea what's messed up
it should work perfectly
in code, it does
but it doesn't actually work
AND NOW DEBUG.LOG DOESN'T WORK EITHER
HOW FUN
I'm done with unity
deubgger doesn't work
console doesn;t work
my code doesn't work for no fricking reason I can't find out w/o all the other things THAT DON'T WORK
I'm fricking done
This is VSC isn't it
it's Rider
Oh nvm then
The lines look like VSC and the debugger is unsupported in VSC
But if it's Rider/VS then the debugger should work
I know
but it doesn't
How can I make my enemy move upright on the navMesh instead of moving around on his back like he is doing now
any idea why the slider value isnt changing? the min and max values chang tho
my brain is fried, I need major help π
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.
I do Equip(StoreItemsVE) on an item, and its putting it back into my itemList.Add space instead of addTo.Add space
Dictionary<ItemType, StoreItemsVE> equippedList = new()
{
{ ItemType.Armor, null },
{ ItemType.Weapon, null },
{ ItemType.Jewelry, null },
{ ItemType.Undefined, null }
};```
EquippedList is not null in these cases, each ItemType has an item
what line is erroring?
Its not
whats your issue then?
I click Equip
(which calls equip)
how r u supposed to make two objects in particular not collide, but activate each other's triggers
do you know how to use your IDE debugger?
no clue what that is
it puts item into arrow on right(itemlist.add) instead of the left like it should(addTo.add)
You can specifically disable collisions between the non-trigger colliders only
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
This is the linked playlist in the pinned message for a tutorial for debugging https://www.youtube.com/playlist?list=PLReL099Y5nRdW8KEd59B5KkGeqWFao34n
Using the debugger tools is really helpful for issues with no errors
this is a multiplayer server game
You can step through code and see what variables contain as the game runs using breakpoints
gotcha thanks, I eventually figured it out anyway π
Is this possible in C# without using 100 lines?
Here if type is not found in the dictionary, it crashes
.GetValueOrDefault
My IDE says it does not exist D:
It's in System.Collections.Generic
Damn I can't find it
alright
can yall explain how this works
if (equippedList[itemType] == null)
{
Equip2(tmpStore, itemType);
}
else if (equippedList[ItemType.Undefined] == null && itemType==ItemType.Jewelry)
{
Equip2(tmpStore, ItemType.Undefined);
}
else
{
equippedList[itemType].equipped = false;
itemList.Add(equippedList[itemType].root);
itemsList.Add(equippedList[itemType]);
Equip2(tmpStore, itemType);
}```
the 2nd else statement is true and it executes
then third else becomes true and executes(since equippedList[itemType] != null anymore)
Shouldn't it have already evaluated the expression and whatever I do in Equip2 not effect the if/else statement?
Oh I get it, i'm using a tuple, and it's non-nullable π
Oh. well then you'd still get a default value
Which would be (0, 0, 0)
yes it shouldnt do the else, are you sure Equip isnt being called twice?
could be possible
it requires a button click...but the menu should go away after its being clicked once
is there a way to do like break; in an if statement?
there's probably a better way to structure your code overall
ok yeah its somehow double calling
since throwing in a return statement didn't fix it inside the if/else
was more just for debugging purposes
How would i do this exactly? it disables both.
Give it the pairs of colliders that you want to ignore
Not 100% sure if it works for your use case but it should
Huh
bc its a multiplayer game
ignorelayercollision
You see, that's a different method
It's not another "version"
Why dont you use IgnoreCollision like I suggested?
players all have their own individual colliders
i can't get and set them all to ignore this one object
well i could, but its incredibly inefficient im sure
there has to be some better way
I mean did you even read the doc?
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
It lets you give 2 colliders
You need to manually call IgnoreCollision for every pair of players, yes
Or put the trigger on a separate child object, and have that on a different layer. Then you can ignore by layer
Lemme know if it works
aight
Can I edit the shape of a freeform 2d light using a c# script?
I have this error when running on android:
unity ads initialization failed: internal_error - unity ads sdk failed to initialize due to environment check failed
this only occurs on android
I have a question regarding the Line Renderer. I use the Line Renderer for a Power Indicator, to show how much power you're applying atm by multiplying the length of the Line Renderer. Though, this issues a problem, since sometimes if I am too close to a wall, and I try to shoot to the left, the indicator would go through the wall. This is not what should happend. How can I manipulate it so, the line is visible at all times, without it going through walls?
Im not sure, but I know its called something where you manipulate the view of the line or something
you should move the line to a different layer
like there's a UI layer
and objects layer
so make another one
There may be a setting called order in layers further down but Iβm a noob and idk exactly where. You can adjust the number to adjust what you can see first
hm
yeah ill try find it but this is everything there is on the tags & layers inspector
ahhhh
wait
its in the line renderer
okay so Ive made background layer and foreground layer
and I assigned the line renderer to the foreground layer
but its still going through the wall
im not able to assign a sorting layer for the walls
I am trying to make a space game. Is there a way to get infinite space in the scene? Because of the floating point limit the meshes start bugging when you get further then 100.000 away from 0|0. I have thought that I could move the planets around the spacecraft so that the physics of the spacecraft don't get effected.
you must use a floating origin system
you should read up about how Kerbal Space Program does it
ok thanks π
I couldn't find anything because I didn't know how it's called
added a breakpoint to this if statement...is there a way to see what it evaluates to before step over/step into?
dont see it on any of the windows what the statement is
you have to step over for it to evaluate
Mouse over the == should display the result
Or use the Immediate window to evaluate it
is there a way so I only debug one script and when I do like stepover it doesn't jump to over scripts running update() code?
Unity does not use multithreading so this can't happen, only one LOC executes at once
use Step Over if you want to step over a function call
use Step Into if you want to step into a function call
I have a prefab "button" (Actually a gameobject that has 3 buttons inside of it /w label) that I am dynamically trying to add to a ScrollView's Content object during runtime. It is fine if I set the parent to anything else it works as expected, but setting it to the scrollview it never shows up.
a good way to deal with this stuff is to test it in scene view
drag and drop the prefab into scene view as a child of the scroll view content
see how it ends up looking
once you get that working properly you'll have it set up correctly to be instantiated at runtime
Also for your Instantiate call make sure you use one of the overloads where you can provide a parent Tranform directly. Without that, your UI element will be instantiated in world space first, which might cause issues (RectTransform might not like being used outside of UI)
if (tmpStore.equipped)
{
popupRoot.Q<Button>("equipButton").clicked += () => UnEquip(tmpStore);
popupRoot.Q<Button>("equipButton").clicked += ClosePopup;
popupRoot.Q<Label>("equipText").text = "Unequip";
}
else
{
popupRoot.Q<Button>("equipButton").clicked += () => Equip(tmpStore);
popupRoot.Q<Button>("equipButton").clicked += ClosePopup;
popupRoot.Q<Label>("equipText").text = "Equip";
}
void ClosePopup()
{
popupRoot.pickingMode = PickingMode.Ignore;
popupRoot.style.display = DisplayStyle.None;
root.pickingMode = PickingMode.Position;
}```
right after ClosePopup() executes it re-runs Equip()
any ideas either why or how to fix that?
(I stepped through it it went and found the root, last line of the ClosePopup)
public VisualElement root { get; private set; }
then immediately jumped back to the
popupRoot.Q<Button>("equipButton").clicked += () => Equip(tmpStore);
and ran it again
You might want to unsubscribe your handlers from these two events, it's never good to leave dangling event handlers especially if you'll reuse the element. Note that you cannot use lambdas if you want to unsubscribe later on, use full methods.
(the same method subscribed twice will get run twice if the event is invoked once)
hmm, never even crossed my mind
where should I unsubscribe at
(Ima go throw all my subscribe stuff into start so I make sure it only subs once)
You usually subscribe in OnEnable and OnDisable, but if you don't plan on enabling/disabling, just destroying, you can do in Start + OnDestroy
awesome thanks!
is there a way to unsubscribe from all handlers in like 1 code line?
or do I need -= for each handler
Depends, what's the type of .clicked? UnityEvent, or plain old C# event?
public event Action clicked
from UnityEngine.UIElements
I have a generated mesh collider which changes each frame (shows what the player can see by shooting lots of ray casts from a point near the cam and making a mesh between the collisions (2D implementation of https://www.youtube.com/watch?v=73Dc5JTCmKI)) (shown in img 1) (Code : https://gdl.space/yenuqazato.cs )
I want to use this to shrink any particles colliding with it in a script, originally I had polygon collider which was a trigger and used the trigger section of the particle system. However, when I make the mesh collider convex it breaks the collider (shown in img 2), from what I can see it needs to be convex to be a trigger.
(here is the working code for the polygon collider trigger based version
[SerializeField] private float shrinkRate = 3f;
ParticleSystem ps;
List<ParticleSystem.Particle> inside = new List<ParticleSystem.Particle>();
void OnEnable()
{
//get darkness partical system when scene loads
ps = GetComponent<ParticleSystem>();
collisionEvents = new List<ParticleCollisionEvent>();
}
private void OnParticleTrigger()
{
//fetch all the particals which collide with a light collider
int numInside = ps.GetTriggerParticles(ParticleSystemTriggerEventType.Inside, inside);
//
//iterate through the particals, shrinking them and if they have a very small ammount of life or they are very small removing them
for (int i=0; i < numInside; i++)
{
ParticleSystem.Particle p = inside[i];
p.startSize -= shrinkRate * Time.deltaTime;
//
if (p.startSize <= 0f || p.startLifetime <= 0.001f)
{
p.startLifetime = 0f;
}
//setting the partical in the list to the modified instance of the partical
inside[i] = p;
}
//
//re-asigning the particals to the partical system
ps.SetTriggerParticles(ParticleSystemTriggerEventType.Inside, inside);
}```
I have tried using a much bigger trigger which gets all the particles that the mesh could possibly collide with to find out whether the particle location is within the mesh bounds through a verity of means but couldn't get it to properly work, I would think this is a good solution but am not sure how to work out whether a position of a particle is within the bounds of the mesh.
Is there a way to do this, or a work around such as making it a trigger without breaking the mesh, using a ParticleCollisionEvent or something else?
so Im guessing basic c#?
So good old C# event. You'll have to -= for each handler you subscribed
fun
thanks π
gosh you are a lifesaver @simple egret
would have taken me a super long time to realize I shouldn't do += inside a callable function π
how would I use full methods instead of +=() => something(needvariable variable)
would I need to declare an actual method that just declares the something method?
Yeah exactly
fun
what would be the reason to unsubscribe my handlers if the script/objects and whatnot are destroyed when scene switches?
In this case you don't need to, but it's good practice, just in case one day you need to persist the object through scene changes and wonder why you get duplicate calls.
Or if you have the subscription in OnEnable and turn the object on/off a lot, you'll get dupes too
awesome thanks π
a key cannot be null . . .
π€
The key is a value type (from the coloring, enum maybe?)
Value types cannot be null, ever
oh, you'rereturning something different than an actual key from a dict . . .
right
basically want to check dict if there is a value in it
if there is, change that value to null
if key is a value type (struct), it cannot be null . . .
therefore, it will always return true . . .
it freaks out from my foreach loop as the list its foreaching is modified in the loop
thus, I need another method :/
There's dict.ContainsKey() that returns bool whether the key is present or not
I only have the value to work with however
Then you're using the dict backwards :)
then check the value instead . . .
π