#archived-code-general
1 messages · Page 269 of 1
well i get an errtor
Can you show the error?
How are you attempting to use CrossSceneDataHolder?
"<myclass> doesnt derived from monoB or SO"
show us the context, not just the single error message
let me get a new log
i'm surprised it mentions ScriptableObject at all if that's the problem, since SOs can't be attached to a game object
It's a generic "not a unity object" error, you can get it if you have a ScriptableObject asset in your project and remove the SO inheritance from it
Ah, I see
Not sure why they didn't just have two separate errors, since it'd be less confusing
i did a test with SO, no errors, but the code didnt work
It's complaining you don't derive from one of the two valid base classes for creating your own unity object, I guess
You need to remove the CrossSceneDataHolder component from whatever it's attached to.
its not attached
You said at the beginning that you had it on a game object
And you won't get that error unless that's the case
Are there any other errors in the log from the build?
console is clean
The build, not the editor
The player-related log locations are the ones you want to look in
Or you can do this
well its the logs im looking at rn
its a plain txt so it not easy to find an error message
ctrl+f for exception
none
In that case, can you add some Debug.Log calls at each part? So we can make sure it's actually running
in the editor it is working
So, once in Restart before it sets InstantStart, once in "elsewhere 3" before it checks the value, and another inside the if block
I know it's working in the editor, but the player can have subtle differences sometimes, so we need to narrow down where the issue could be by determining what is actually running
i know it because, to be short, my menu dispears and the player can move if InstantStart == true
mb i forgot that debug logs shows in the player logs
thats why i thought you were talking about the editor
found the issue
unrelated to CrossSceneDataHolder
ty Zombie and Fen for helping
What was the issue, out of curiosity?
for some reason, a get component is failling
so my code that tiggers this doesnt get trigger
but, why only in build ?
I might have a hunch, can you show how you're doing that GetComponent and how you're checking it?
awake
I mean, the actual code, it's a very specific issue if it's what I think it is
it does a get tag then a get comp, maybe the player didnt spawn
but it always work in editor, and never in build
private void Awake()
{
_player = GameObject.FindGameObjectWithTag("Player");
_playerC = _player.GetComponent<PlayerController>();
_animator = GetComponent<Animator>();
Cursor.visible = false;
Debug.Log("Check CrossSceneDataHolder.InstantStart :" + CrossSceneDataHolder.InstantStart);
if (CrossSceneDataHolder.InstantStart)
{
CrossSceneDataHolder.InstantStart = false;
Debug.Log("Check CrossSceneDataHolder.StartInTuto :" + CrossSceneDataHolder.StartInTuto);
if (CrossSceneDataHolder.StartInTuto)
{
CrossSceneDataHolder.StartInTuto = false;
StartTutorial();
}
else
{
StartClick();
}
}
else
{
if (!PlayerPrefs.HasKey("NewPlayer"))
{
_navigationSelectables.RemoveSelectable(0);
PlayButton.SetActive(false);
PlayerPrefs.SetInt("NewPlayer", 1);
}
}
}
public void StartClick()
{
_playerC.UpdateMenuStatus(false);
_animator.SetBool("Fade", true);
_statsCanvas.GetComponent<Stats>().Fade(true);
_navigationSelectables.DisableInputs();
_playerC.InTutoLevel = false;
}
Does Start trigger on Instantiate?
_playerC.UpdateMenuStatus(false); is failling in build
Ok yeah, I think I know what the issue is then
im all ears
So, in the editor, GetComponent will not return null for a missing component. It will return a new instance that represents a "fake" null, and will throw an exception when you call Unity methods on it (but your own methods will still run)
In the player, it will actually return null
The reason the editor does that is so it can throw MissingReferenceException instead of NullReferenceException, but imo the tradeoff is not worth it because it causes problems like this
if its a fake null, how does it still get my player ref ?
in editor
Because it's still a real instance on the C# side
okay
So, anything inheriting from UnityEngine.Object (including MonoBehaviour, etc) is kinda like this:
public class Object
{
private IntPtr nativeObject;
}
When you get a fake null, it just has an "invalid" object assigned to nativeObject, so when you try to call engine functions on it, it will throw an exception. But your own functions don't know about that, so they will run fine (unless they also call engine functions themselves)
It's very stupid and it's a bad design that has plagued Unity from the start
this sounds interesting what's going on
tl;dr unity's fake null causes yet another person headaches
I didn't know fake null was a thing
That's the fun part! It tries to hide it from you but fails to do so in cases like this
The issue seems to be that PlayerController isn't on the game object you get from GameObject.FindGameObjectWithTag("Player");
worked
how do you have a "missing" component as opposed to the component just not being on the object?
Do you add PlayerController through code instead of the inspector? That'd explain it
It's a special instance that Unity creates for the sole purpose of throwing a different exception
hey, is fishnet the best solution for easy multiplayer ?
even with a FindFirstObjectByType
it didnt work
nope it already exists in the scene
does unity load in order the scene GOs ? or is it random
I assume the problem is that StartClick is running before Awake does
Is the game object with this component on it disabled?
like from top to bottom in Hierachy
Unity will automatically put "fake null" instances into any serialized component fields too
StartClick gets called from Awake
So it's not called by anything else outside?
But if the game object is disabled, Awake doesn't run
nothing is disabled
I mean how would you even make that happen
(I'm just really fascinated)
Unity creates an uninitialized instance of the object, and modifies the private field that references the native object
hm alright
I've never had this happen
so I will live ignorantly in bliss until it does
why cant I get the first item of the array ?
It looks like at some point they changed it so it doesn't do it for custom MonoBehaviours anymore, but it does it for built in ones still
Debug.Log(GetComponent<Camera>().GetInstanceID());
This will print 0 in the editor, but it will throw an exception in a build
(If there is no Camera component)
Because you didn't invoke the function
GetRootGameObjects()[0], not GetRootGameObjects[0]
i forgot its a function
ty
by the way
SceneManager.LoadScene("Tuto", LoadSceneMode.Additive);
SceneManager.GetSceneByName("Tuto").GetRootGameObjects()[0].SetActive(false);
will this not cause an error ?
since LoadScene will execute at the end of the frame
It might work in the editor since scene loads seem to always be synchronous there, but yeah, that probably won't work in a build
var operation = SceneManager.LoadSceneAsync("Tuto", LoadSceneMode.Additive);
operation.completed += _ => SceneManager.GetSceneByName("Tuto").GetRootGameObjects()[0].SetActive(false);
(I wouldn't recommend hardcoding the index of a game object in your scene though...)
GetRootGameObjects is a method
and you can't access a method with a array indexer, you have to invoke with (), then use []
Can someone help me rq with an issue?
unity is thinking im running multiple instances of the same project, when im not
ive restarted unity, my comp, and uninstalled my editor version
and reinstalled it
screenshot your project folder contents
Good morning all! I'm attempting to make a top-down pixel art game with intuitive tool useage. So if you're standing in front of a tree, you will use your axe if you press interact, if it's a mining node, your pickaxe, etc. What would be the best way to handle the interaction button handling to find the appropriate object, and communicating with it? So like when the player presses interact, we find the most likely object they're trying to interact with, choose the appropriate tool, start the swing animation, and midway through that animation when the tool would "connect" with the object, communicate to the object that it has been interacted with. Should I use raycasts in the direction facing? Is that the best method, or is there something more accurate?
Do you typically set the position of something in the same function where you instantiate it?
I have a function thats called from another class to instantiate an AI agent, should I pass the Vector3 into there and set it or should I return the gameobject and have the class that called it set it?
why does this rotate my object to the nav mesh agents target and not the nav mesh agents next position on its path?
I'd probably just put a box collider as a trigger in front of the character based on their reach length
me?
yes, you
like the folders or in the engine
it's unlikely to be in the engine if you can't open the project is it?
i can open it it just doesnt export cuz of it
that is not what you said
That's an interesting idea I haven't tried yet.
you mean build
yea im new to this
I can tell, no one in their right mind would make a project in the Downloads folder
where should i put it
Anywhere that is not a Windows special folder
Also your bundle has no output path specified
close the project, move it somewhere sensible then screenshot that folder
where do u put yours usualy
in a Unity folder
mine was sent to me to do something with to i have no clue where those are
you do know how to make a folder I presume
no just in the root of your drive
kill the project
i did
Hey all. I want to make an enemy respawn system for a metroidvania like game. To do this, when an enemy is killed ill spawn a "grave". Now when the player exits the current room collider, i want all these graves to trigger a respawn of the enemy. How do i get all objects tagged or on layer "grave" within a polygon collider2d?
There's much efficient way to do that, which is store every grave in a list as it spawns , there you go
oh yeah true i guess ill make a dead enemies list and if player enters a new room respawn it
always taking the harder road damn lol
thx
i moved it to my drive root, and removed the project from my list, reloaded it and it fixed
thought it might. lesson of this is never use Windows special folders for your own stuff
still doesnt want to build tho
You could use a raycast from your player/camera for accuracy, or maybe a capsule cast if you want to be a bit more generous with player precision, if your nodes, trees, etc have a shared interface like maybe a IInteractable setup, then you can use that or a base class to inform it that its "been connected with", this way you can call something like a .Interact() on the object and not need to know any details about the object, if you do need to know specifics (maybe to display "collecting lumber..." or something), you can have the interface either have a function or a property that returns that info, each class can override that property/function passing its type or relevant info
Usually ill include a position and optional parent param for local/world space positioning, if I feel like whatever was instantiated will need to be modified beyond its Transform, then I would have the function return it too
Is BuildPlayerOptions.locationPathName relative or a full path
I'm trying to make a script to create directories to put my builds
@knotty sun it still wont build tho
check your editor !logs
By the description on the docs, im going to guess its a full path (https://docs.unity3d.com/ScriptReference/BuildPlayerOptions-locationPathName.html), though you can always log it to find out, your project would exist at Application.dataPath which gives you the path to your project, then /Assets, so you can remove the last part to get the root of your project, I typically make a "Builds" folder in my project root, sometimes organized by version: https://docs.unity3d.com/ScriptReference/Application-dataPath.html
Hi. Does anyone know how to solve the following error:
ArgumentException: Expecting value of type 'Single' but got value '(0.00, 1.00)' of type 'Vector2'
Parameter name: value
The code is the following:
float valMag = 0;
object obj = action.ReadValueAsObject();
if (obj == null)
{
return;
}
Type valueType = obj.GetType();
if (valueType == typeof(float))
{
valMag = (float)obj;
}
else if (valueType == typeof(Vector2))
{
valMag = ((Vector2)obj).magnitude;
}
else if (valueType == typeof(Vector3))
{
valMag = ((Vector3)obj).magnitude;
}
post to a paste site
wut
!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.
use the large code option
Which line specifically is giving you this error?
when I click on the error, it takes me to the second line in there, the "object obj = action.ReadValueAsObject();" one
Interesting, usually that error means your reading your action as a different type than you setup in your action map, in this case your action seems to be a "Single" and its trying to read it as a Vector2, maybe there are limits with "...AsObject"? Or something else could be a factor
I don't know. That is happening when I'm trying to use the scroll axis on the mouse wheel
I wouldn't expect that to happen.
is there a reason you need to be able to handle all of these different types?
thanks!
because I don't know which type the action will be. Like it is for a rebinding system, but I guess I'll just have to go around it
Did you just change it from action.ReadValue<float>() ? I wonder if you just didn't save or something
Yeah previously I was using that action.ReadValue<float>(), but for the scroll wheel didn't work
it's plausible that unity just hasn't recompiled
make sure it's done that :p
The error would take you to the line number from the old script
which would probably line up
so like I should recompile it but with what? The "action.ReadValue<float>()" or the code I sent first?
the code you sent, but...just make sure that unity actually saw the new code!
Now, had you even bothered to read the end of that you would see exactly what the problems are. There is error after error after error there
where, i dont see it, but im probobly looking right past it
i see 1 of them
Start at line 4,829 and go from there. Btw these errors have absolutely nothing to do with Unity but with LeathalSDK so you should ask for more information there
alr
hmm, I tried recreating this myself and got some interesting results
ReadValueAsObject() returned null when I called it on a Vector2 action
this is on an InputAction, not on a CallbackContext, mind you
but it didn't complain about a type mixup
I mean it doesn't return anything when I don't move the mouse scroll wheel, the error appears when I move it😅
well first thing, why is the scroll wheel even a Vector2D???
because you picked a Vector2 input control
mouse wheels can often tilt to go horizontally
Oh I didn't know that
If you want a single value, switch your input action to an Axis and then pick something like
Wtf
<Mouse>/scroll/y
I didn't know that either
you're probably using <Mouse>/scroll
Hey i'm having trouble with rotations using angularvelocity to align an object rotation with a grabber's rotation. The issues are:
When approaching the negative Z direction in world space, rotation becomes extremely jittery, and even skips completely over the negative Z direction. This issue persists with both setting the angular velocity, and simply using Transform.LookAt() to store a value, then set the rotation of the object to that value with a change in the Z rotation.
As well as, when using Transform.LookAt(), the closer the object gets to the negative Z direction, the more misaligned it becomes with rotation of the Grabber. Will send a short video as well as a code snippet from all rotational changes.
TWO HANDED GRAB
public virtual void LookAtSecondary()
{
//Rigidbody rb = GetComponent<Rigidbody>();
//Adjust Angular Velocity to rotate to hand
//rb.maxAngularVelocity = 20;
Vector3 eulerRot = secondaryGrabbable.transform.position;
//eulerRot *= 0.95f;
//eulerRot *= Mathf.Deg2Rad;
//rb.angularVelocity = eulerRot / Time.fixedDeltaTime;
transform.LookAt(eulerRot);
Quaternion r = transform.rotation;
r.z = mainGrabber.transform.rotation.z;
transform.rotation = r;
}
ONE HANDED GRAB
public virtual void GrabbedRotation(Transform rot)
{
if (GetComponent<Rigidbody>())
{
Rigidbody rb = GetComponent<Rigidbody>();
//Adjust Angular Velocity to rotate to hand
rb.maxAngularVelocity = 20;
Quaternion deltaRot = rot.rotation * Quaternion.Inverse(rb.transform.rotation);
Vector3 eulerRot = new Vector3(Mathf.DeltaAngle(0, deltaRot.eulerAngles.x), Mathf.DeltaAngle(0, deltaRot.eulerAngles.y),
Mathf.DeltaAngle(0, deltaRot.eulerAngles.z));
eulerRot *= 0.95f;
eulerRot *= Mathf.Deg2Rad;
rb.angularVelocity = eulerRot / Time.fixedDeltaTime;
}
}
!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.
yeah. Okay I'll try to use the Y axis as you said. Thanks 😄
How do you use this thing???
Yeah but it doesn't say that with the default overload but i can't use it because it becomes this by itself
i think those are for a example mod
and when choosing and InputControl, do you know if is there a way to check if it will return a float please? So the player can only select inputs that will actually return floats
I think only one or two overloads are deprecated
Might wanna ask in #↕️┃editor-extensions
Oh thanks
why is the .unity3d file becomeing .unity3d.tmp
I don't know about that. I haven't done rebinding yet
Find the overload that's not deprecated that you can use
[performs the sign of the cross]
god willing
I'll probably be figuring that out soon though, haha
You have to be able to filter that, though
Oh you know what -- I bet that's why you got the error even though you used ReadValueAsObject
oh okay. Well if you aren't using the rebinding ui extension already with unity because that's not good enough, don't try to make your own, it is BAD, real bad lol
It's because the input action is set to produce a float and you gave it a control that produces a Vector2
That makes way more sense now
okay then I have to limit what the player can actually bind it to lol
fixed it
So there is nothing in the docs
Nice
I'll go ask in #↕️┃editor-extensions
it was set to any tho, but yeah I'll just force it into being a float haha, thanks 😄
huh, I'm actually not sure how that behaves
why does this not work, I get this error Error CS8377 The type 'Farmland' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent<T>(Entity, in T)' Assembly-CSharp
Maybe ask in #1062393052863414313
But what type is Farmland?
A struct
Just a plain struct, inheriting from nothing?
Inherits from IComponentData
Ok, just making sure
Ah, don't use a constructor
Might be the issue?
At least, I never do. Just new ComponentType( field1 = whatever)
But yeah, check in #1062393052863414313
I added the constructor to try and get rid of the error I origionally had what you said before.
String is not a value type
As the error says everything has to be a value type
If you want to strore a string in an unmanaged type, you need to use one of the fixed-length strings provided by the ECS packages
(i forget where exactly it comes from)
I think Unity.Collections
if it works similar to the NGO fixed string
unless ecs has their own version 😛
Guys, is there any way to fix this? I want my bullets to come out of the gun and after being fired to focus on the camera but not suddenly, but little by little they become centralized in the camera when fired, here is the code I use
Vector3 direction = (crosshair.transform.forward - bulletSpawn.transform.forward).normalized;
Rigidbody rb = bullet.GetComponent<Rigidbody>();
if (rb != null)
{
rb.velocity = direction * shootForce;
}
the result (they don't get fired) =
(crosshair.transform.forward - bulletSpawn.transform.forward) <-- this doesn't make any sense
just make the bulletSpawn object point where you want the bullets to go, then it's just Vector3 direction = bulletSpawn.transform.forward;
I want to imitate it like half life 2
so look at the half life 2 code
Anyone familiar with the new AI Navigation package (and its gizmos)? Recently upgraded from 2021 LTS to 2023 and I'm seeing some new weird behavior where some of my enemy agents are jittering. The cyan arrow gizmo is also flicking back and forth so thinking it might be related, but I'm not sure what these arrows are supposed to represent!
Red is your Path
Light Blue is your Direction iirc
Thank you! Is this documented somewhere? The overlay menu toggles don't seem to correspond to these arrows. Also there are actually 2 red arrows.
how long is the path?
It's just the path from this beetle enemy to my player. In that screen shot somewhere around 10 units?
Red = Path, path corners
the dotted meansoff navmesh
Blue arrow is direction to destination point
red circle is the spot where it can reach max, since thats where navmesh ends
I'm making irregular "zones" that trigger ambient sound and weather effects. For the sounds I made a system where I have a counter incremented on enter, and decrement on exit, so I know if the counter is 0 I'm out of all triggers. Before I factor that logic out, is there an easier way?
For rigidbody colliders I can have multiple and they will act as a single collider on the body. Is there a way to have multiple trigger colliders act as their "csg sum"? When I attached multiple colliders to an object it doesn't work I get ontriggerexit called on individual ones.
Thanks! Mine does look a bit different though. Here's a view from above.
looks the same to me
ur just more zoomed in and ur gizmos look bigger
No dotted line, two red lines and a transparent arrow.
RedLines means they are path on the navmesh
dotted I told you earlier means the path is off the navmesh
its hard to see on mine but its there
same way
I understand what the dotted line is mean to represent, but I don't have a dotted line in my view, just two red (non dotted) lines
I suppose the thing I'm more curious about is why the agent's direction seems to be going haywire. The destination is unchanging.
I just told you why its not dotted..
dotted means the path is not on the navmesh
also Youd have to show your code and how do you call the destination
can someone help me, unity keeps making the unitystream.unity3d file to unitystream.unity3d.tmp. anyone know why?
you are not doing much to explain, but chances are the problem is beause Destroy does not happen instantly
also explain what the issue is
what the expectation was and what is happening instead
ok so in the code i destroyed an object
and it is a variable
but when i reassign the variable in the line below it
it says an error
missing reference exception
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
im getting this error and idk how i can fix it, it all seems right to me
https://paste.ofcode.org/gTuBwLX8ejkHJMdBY4HB9c
https://paste.ofcode.org/8PZhUqpVY5xf3juh7G4ATF
error:
Assets\Scripts\Player.cs(46,26): error CS1061: 'ClearCounter' does not contain a definition for 'Interact' and no accessible extension method 'Interact' accepting a first argument of type 'ClearCounter' could be found (are you missing a using directive or an assembly reference?)
I have a tower defense game where the thing being protected is a Brain. The Brain class is not static but has some static variables like health. At the end of the game you can restart the scene, but these static variables are not reset. It appears from some research this is because their being set at the class level so i would have to manually reset them at the beginning of a scene. This is not optimal.
Is there a better solution i can look into? I'm looking for a best practice, not just a work around
gimme a minute
alr ty
dont have them be static
that way you can just destroy and recreate the object and everything is back to its starting values
Have them not be static causes a lot of coupling which is not a great practice
its still coupling if they are static
try putting "public ClearCounter clearCounter" this will ensure the script is loaded by the script, make sure the clear counter script is referenced in the inspector
yes, your other things accessing the static vars still depend on them
They exists because the class exists, they dont depend on an instance, making them not static couples them to an instance
@cobalt tendon if you didnt see
but you want them to act like a instance since you want them to reset
only thing that resets static stuff is a full domain reload which is not something you can really do in a build
ok so i added the public thing but it didnt work and then i deleted it again and it compiled and it somehow worked?
its the exact same code as before and it worked..

so you will either need logic that resets them, or put them on the instance
the wonders of c#
Thats fair
Im, for the funsies, trying to replicate the Rigidbody component, but im having trouble with the rb.addforceatposition, does anyone know how I could implement it?
public void AddForceAtPosition(Vector3 force, Vector3 position, ForceMode mode){
float divider = mode == ForceMode.Acceleration || mode == ForceMode.VelocityChange ? 1 : mass;
Vector3 linear_acc = force / divider;
Vector3 angular_acc = Vector3.Cross(position - position, force);
_newVelocity += linear_acc * Time.deltaTime;
_newAngularVelocity += angular_acc * Time.deltaTime;
}
Does this look right?
Any idea why my AI is not moving on a NavMesh that was generated during runtime using NavMeshSurface? It's showing an error "GetRemainingDistance" can only be called on an active agent that has been placed on a NavMesh."
Can you change Scriptobjects with code?
I tried to do that, it worked, but somehow, it reverted!
well that is why, your agent is not on the mesh
does nobody read error messages?
It is tho
You can, but as you experienced they get reset when the app restarts. In the Editor it's a bit different, they reset when you restart the Editor, not a play mode session.
As such, scriptable objects should not be used as save files, and should be treated as immutable (cannot be changed)
When i bake the mesh normally, it works, but when i bake it with the NavMeshSurface on runtime it doesn't detect it.
I see
Is there a way I change modify scriptobject's data without doing that?
It's over 100 objects I need to change to a new format
also good idea to isntance them in memory if you dont want players in editor messing with the data on your assets
You still can modify their values at runtime, but if you want to restore the changed values when a new instance of the app starts, you need to save them somewhere (to a file, for example), and load them when the game starts
If I copy/paste would it work?
No I mean via code, at runtime. You don't have access to the Editor on builds, and the game data is not easily accessible by the user (it's packed in a few asset files)
hello ! can someone help me please, when i start my game, my model go down on the "Y" with the rigidbody component enable. Do you know why ?
Oh, I see
I mean, I am in the editor & at runtime
I think there's a misunderstanding on what the question means
Can you rephrase it with more context? What are you trying to do, globally speaking
what is your model standing on?
On a terrain with collider terrain, i can share a picture of my prog if you want.
does your model also have a collider
show the terrain inspector
Alright, sure
I am working on re-structuring my weapon's variables
It's basically the same variables, but in a different, easier to use format
Because while I could do update the new variables with the old variables by hand, it would be easier to use code to copy/paste the variables
When I did it, it worked and changed the scriptobject variables, then I went and deleted the old variables and updated the project to use the new variables
When I tried to test the new weapons, all the updated variables (Using code) reverted back to what it was before
not to but in but I was curious what other people's variable and script naming conventions are
idk dude try it but I fw this
The C# conventions are pinned to this channel
I have read that yes
why is my velocity being printed as 0?
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * currentSpeed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
Debug.Log(new Vector3(controller.velocity.x, 0, controller.velocity.z).magnitude);```
you cant set vectors like that, assign velocity to a temp var, increment y assign it back
because you only set the y value but print that as 0
but im moving my controller
how are you moving it
top 2 lines
The last we see of you moving it is solely on y
And Character Controller is whack and afaik it's "velocity" is just the last move
huh
ah
i moved my debug statement to before velocity.y and it's displaying the magnitude fine
so it just the last move stuff
Hi, is there a way to programmatically create the InputActionsAsset in my project folder? I've tried with AssetDatabase but it returns these errors
UnityEngine.StackTraceUtility:ExtractStackTrace ()
Babbitt.Tools.Editor.ProjectFolderSetupWizard:InitializeInputFolder (string) (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:134)
Babbitt.Tools.Editor.ProjectFolderSetupWizard:OnWizardCreate () (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:73)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type)
at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x0005f] in <1a33381171f2411d8ffae255a64550dd>:0
at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in <1a33381171f2411d8ffae255a64550dd>:0
at UnityEngine.InputSystem.InputActionAsset.LoadFromJson (System.String json) [0x00013] in .\Library\PackageCache\com.unity.inputsystem@1.7.0\InputSystem\Actions\InputActionAsset.cs:382
at UnityEngine.InputSystem.Editor.InputActionImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) [0x00074] in .\Library\PackageCache\com.unity.inputsystem@1.7.0\InputSystem\Editor\AssetImporter\InputActionImporter.cs:76 )
UnityEngine.StackTraceUtility:ExtractStackTrace ()
Babbitt.Tools.Editor.ProjectFolderSetupWizard:InitializeInputFolder (string) (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:134)
Babbitt.Tools.Editor.ProjectFolderSetupWizard:OnWizardCreate () (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:73)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
If it isn't possible then fine I'll work around it.
I'm making a script to generate project folders for a new project
I've figured out what the problem is with my code, but I don't know how to solve it. Currently, the slope detection in my script is added by using the IsGrounded() method to check the normal of the ground the player is on. Then it converts the normal of the ground and the normal of the player to an angle. Then it says, if the angle is greater than 0, then the player is on a slope. And then using the slope detection, it says if (IsGrounded() == true && OnSlope() == false) verticalMove = 0; Basically meaning that the only vertical movement being applied while on a slope, is gravity, causing the player to fall back down the step really quickly because the gravity is constantly being applied.
I added the OnSlope() section because if I don't, the player hops when going down the slope: https://streamable.com/y6g5r9
void FixedUpdate()
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, radius, objectsLayer);
foreach (Collider2D collider in colliders)
{
// Set the objects within the radius to active
GameObject treeObject = collider.gameObject;
if (treeObject.CompareTag("Tree"))
{
SetTreeObjectState(treeObject, true);
}
}
// Set all other objects to inactive
Collider2D[] allColliders = Physics2D.OverlapCircleAll(transform.position, Mathf.Infinity, objectsLayer);
foreach (Collider2D collider in allColliders)
{
if (!colliders.Contains(collider))
{
// Set the objects outside the radius to inactive
GameObject treeObject = collider.gameObject;
if (treeObject.CompareTag("Tree"))
{
SetTreeObjectState(treeObject, false);
}
}
}
}```
Hi, I am trying to have objects load in certain components based on being in a radius of the player. It works, however, it is not performant. With a random map, at 500x500, there is serious slowdown with the contains line. Is there a faster method of checking if the collider is not inside the radius instead of !colliders.Contains?
Would a hashset be more performant?
You say
if the angle is greater than 0, then the player is on a slope.
What angle is the steps? And do you plan to have any surfaces in your game (that are walkable) that also match those angles?
Going down slopes, you should be able to use Vector3.ProjectOnPlane, though for stairs, it sounds like your logic already ignores that condition with a false check
does anyone know how to use shadergraphs?
why use a overlap circle to get all trees, you could just maintain a collection of them yourself or FindObjectsOfType
FindObjectsOfType is extremely laggy
Im having trouble with reflection and a divide node
I could make a list of all trees though, thats a good idea
Let me implement that!
also you could just loop all of them, from your collection of all trees, and see which ones were in the first overlap circle
no need to loop twice
I want the Order in Layer to be set to 1 every time a line is drawn. I've set it to 1 on the inspector but when it instantiates its set at 0. If anyone can help much appreciated
That asset usually generates code for the data inside it, and then also creates a custom type matching the name of the asset (by default), so maybe its not as straight-forward as just creating a new asset of its type, what line of code are you using to try and create the asset with AssetDatabase? And is the type your creating from one that already exists in your project or some base InputActionAsset? It likely may be easier to clone an existing file and import it to your project - if you have a folder you often keep projects in, you can use that like a "local repository" and keep an input action asset youd want to copy to multiple projects in, so you can locate it from any project (by for example, getting the root of your current project, then back-naving to your "local repo") - there are other ways you could handle imports as well such as a unitypackage, or prefab or something similar as well
Makes sense, thank you!
The angle of the sharp part of the steps moves from 90 to 0 as I go up a step.
I'm calling this function after generating a folder
{
InputActionAsset inputAction = new InputActionAsset();
inputAction.name = "GameInput";
AssetDatabase.CreateAsset(inputAction, $"{path}/{inputAction.name}.inputactions");
}```
Maybe .sortingOrder?
Do you plan to have walkable 90 angled surfaces in your game, other than steps? If not, you could create a condition for your slope logic to ignore 90
The issue is that the angle variable doesnt equal 90 on the step corners, here is a video of what I mean: https://streamable.com/r23z11
Is the type .inputactions? I thought it was just .asset though I doubt it would create the file you expect, it should at least work without error
why not just keep it simple and fake it, just have a collider that is wedge shaped over the stairs that is not visisble
Thanks!
Because for my game it looks nicer if the player looks like they are actually walking up the stairs, rather than sliding up.
.asset just makes it a scriptableobject
guess there is no built in way to do this,
well so you will do IK targets for feet positions later?
though a workaround could be to just do a few raycasts, have one slighty infront of your target incase the first hits the corner
No, thats overly complicated for animations, I mean from the first person perspective, it looks nicer to jump up each step rather than slide up them like a ramp.
Huh, your right I guess it is .inputactions my only other suggestion might be to either work around it with a pre-made action map, or maybe peak the source code of the Input package and see if you can find the Editor script that the context menu uses to create a new action map and try to replicate that code, though it sounds like a "more trouble than its worth" approach
yeah, that's the vibe I'm getting from this conundrum, I'm just going to drop it and create it manually
thanks for the suggestion though
This worked great. Over 200fps now on a massive map. Thank you so much!!
Sometimes you get so stuck in doing it the way you want you forget the alternatives
can anyone give me advice on how to optimize OnTriggerEnter performance wise?
you are not really giving enough information
sorry, in my game projectiles can chain to the next enemy and when a lot of enemies are stacked, Physics2d.CompileContactCallbacks is taking up most of my memory in the profiler
It's pretty optimal already. It only triggers when you enter. What is the code inside?
!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.
Does DirectionTowardNearestEnemy get called often 👀
You have 3 methods called that can be optimized . . .
DirectionTowardNearestEnemy is eyewateringly bad
You're using a GetComponent call in each of them that should be cached . . .
yeah see a few things that can be cached, and directionTowardsNearst enemy could be greatly improved
yeah it gets called every chain lol
The DirectionTowards method creates a list each time and uses linq which will produce gc allocs . . .
also contains check on a reglar list
how should I optimize it
and a sort
- Use the non-allocating version of OverlapCircleAll
- Don't use
.ToListunless you absolutely need to, that allocates an entire list every time it's called.
yeah not needed in this case since its jsut a orderbyand a .first that comes after
though would use a HashSet for enbemiesAlreadyChainedTo
you need to cache the Collider2D and Rigidbody2D component since they're accessed in all of the methods . . .
much faster contains check, and would do it all in 1 loop from the result of OverlapCircleAll
can loop skip the needed items and keep track of the distances and current nearest in 1 loop which is less costly then a full sorting of it
in OnTriggerEnter use TryGetComponent for IDamageable. you don't check if it's null before accessing and passing it to Chain, though you check it for null within that method . . .
No need to use GetComponent to get any rigidbodies or colliders when Collision2D already has them
also would make sure the collison matrix is ok, and its not doing on trigger for more things then needed
thanks, also, should I not use rigidbody for projectile physics?
only thing you need get component for in this is the IDamagable
wdym collision matrix
defines what layers are aloud to collide with what other layers, when it comes to the OnTriggerX and OnCollisionX stuff
if nothing else is triggering the collisions does it matter that its all on?
that's right, totally forgot about that . . .
other little trick is you dont need to compare distance directly to get closest
Turn everything off that isn't ever gonna collide with each other. When I start a project I turn absolutely everything off
sqrMagitude is cheaper to calculate
But I also care about that performance more than the usability of having to touch those settings every time I do something new
wait how would I use the nonalloc circle if it just returns int
the int is the count of hits
you pass it a array it files in place
it returns the number of colliders hit . . .
that way you can allocate the array once and let it fill it
https://docs.unity3d.com/ScriptReference/Physics2D.CircleCast.html
Returns
**int **Returns the number of results placed in the results list.
you pass in an array with the size you expect to be hit. it will only fill up to that amount. any more hits will not be recorded . . .
Or you just use the one with a list
you pass it a array large enough to hold the possible hits
and it fills it for you, then returns how many items it put in it
yeah, but i like a set number. 10 and nothing more, lol . . .
ah i see
you create the array as a class field . . .
didnt realize it took the array as an input
it allows you to allocate the array up front, and just keep reusing the same array and memory instead of creating it anew
initialize it at declaration or in Start or smth . . .
and yeah nonalloc really is a saver, shaved off 30ms and over 1KB of garbage
https://docs.unity3d.com/ScriptReference/Physics.RaycastNonAlloc.html
i know its for the 3d physics and raycast but shows a example of how the nonalloc ones work
wait so what should I do inplace of the linq sorts and removes
you could get the results from the overlap circle and loop them, setup a if statement that does a continue for the ones you want to skip based on if in that collection or not
then keep track of the min distance in a variable, and the object you got that min distance with
when you loop is done you will have the one with the min distance
also changing enemiesAlreadyChainedTo to a HashSet will make contains checks on it much faster
also could use MinBy instead of OrderBy even if you wanted to use linq
though i would recommend just doing it all in a loop
honestly, i've only ever used the NonAlloc. typically, you'd know how many objects will hit . . .
yeah i more or less only use the non alloc versions, generally have a good idea of how much i need to check
There's no reason not to use it
Unless you're lazy and don't want to write that teensy bit more code
also just closer to how i would do this kinda stuff in C, where i am often holding on to memory and reusing instead of spamming the crap out of malloc and free
So I am watching a tutorial on how to stylize bloom shader into comic style circles, and it gives me an error in the shader pass processer that 'source' is null value, any way to fix it?
once you write an extension method for GetClosest (object) or GetClosestPoint you can use it for everything since it's a common thing to do . . .
oop
it sort of working and is a lot faster but im getting a few errors of MissingReferenceException: The object of type 'BoxCollider2D' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Projectile.DirectionTowardNearestEnemy (UnityEngine.Collider2D excluding) (at Assets/_Scripts/Equipment Logic/Projectile.cs:77)
https://gdl.space/fudasapogi.cs
can't seem to figure it out
You are not using the result of OverlapCircleNonAlloc
And instead you're just iterating the whole array as if it's got values assigned to it
you need to use a regular for loop
and only loop as high as the returned hitcount from OverlapCircleNonAlloc
Collider2D closestEnemy = enemiesNearby[Random.Range(0, enemiesNearby.Length)];
can just start it off as null too
but you do have the right idea with distance start it at Infinity or really any number above your radius
There is no need to check if enemy is null
if I set it to null i get a bunch of errors
no need to calculate the distance twice
as far as vector ops go its a more expensive one
it should start as null, and then you check whether it's null at the end, because it can be null if you skipped all the enemies because they were already chained or excluded
yeah that should be greatly faster
yeah its insane now
after that in the orginal code only other parts were all the GetComponents
so all of those that were getting stuff on the projectile you could just do in Awake and cache on a field
is it better to reference the component in the inspector or get it in Start
the colliders on collisions you already have direct access to
makes little difference, either way its only happening once. technically doing it via inspector will be best
but very small difference compared to cleaning up that 1 function
kk
so like using linq, it can be a ok time saver in code that only runs once, but i tend to avoid it for anything that could be happening per frame or multiple times a frame
so just use arrays when updating per frame
yeah per frame stuff or things that happen very often good to try and avoid reallocating stuff every time
if it's the same object, just manually assign them, it's easier . . .
you can even have a check in Awake . . .
I'm trying to add knockback to my game, however with the following code, the distance of which you are knocked back is very inconsistent and unpredictable.
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject == player)
{
playerFlashTimerActive = true;
if (!collisionCompleted)
{
playerRigidbody.velocity = Vector2.zero;
playerDirection = (player.transform.position - transform.position).normalized;
playerRigidbody.AddForce(playerDirection * playerKnockback, ForceMode2D.Impulse);
collisionCompleted = true;
}
else
{ StartCoroutine("knockbackTimer"); }
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject == player) { collisionCompleted = false; }
}
IEnumerator knockbackTimer()
{
yield return new WaitForSeconds(knockbackDuration);
playerRigidbody.velocity = Vector2.zero;
}
How could I alter my code so that the knockback is a consistent distance every time?
Reset the velocity before doing AddForce
wait you're already doing that
nvm
yeah
should be farily consistient
though will have a extra frame or less 1 frame
before the reset
Knockback timer can't start the same frame as the addforce
It doesn't
also you never cancel the timer, might get weird cases with multiple knockback timers going at once
if like hit 2 or 3 times quickly
So velocity could be set somewhere else before the timer starts. Show the movement code
It really should
what do you mean by cancel the timer?
alright i'll change that
if you got hit twice in a smaller duration of time then the timer, you would have 2 timers going that each will zero your velocity at different times
when you start a coroutine you can cache its result to a field so you can stop it later if it did not already stop on its own
i've already debugged the movement code, does not affect velocity
can you provide code for how i would go about that?
Are you moving with transform or MovePosition?
velocity
Then... it affects velocity clearly
i have conditions so that velocity wont be affected during knockback
like i said, i've debugged the movement code and it does not affect anything
I assumed so, that's what I wanted to check the logic of. We can debug things incorrectly.
But if you don't want to, that's fine.
I feel that is the most likely culprit though, or the frame disparity that passerby mentioned
Not trying to sound snarky or anything btw. All good!
I can attach it, it's just long and I didn't want to burden you with that.
Give me one minute
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.A))
{
movementJustStopped = true;
}
if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.D))
{
myRigidBody.velocity = (Vector2.up + Vector2.right).normalized;
animator.SetBool("isWalking", true);
}
else if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A))
{
myRigidBody.velocity = (Vector2.up + Vector2.left).normalized;
animator.SetBool("isWalking", true);
}
else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.D))
{
myRigidBody.velocity = (Vector2.down + Vector2.right).normalized;
animator.SetBool("isWalking", true);
}
else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.A))
{
myRigidBody.velocity = (Vector2.down + Vector2.left).normalized;
}
else if (Input.GetKey(KeyCode.W))
{
myRigidBody.velocity = Vector2.up;
}
else if (Input.GetKey(KeyCode.S))
{
myRigidBody.velocity = Vector2.down;
}
else if (Input.GetKey(KeyCode.A))
{
myRigidBody.velocity = Vector2.left;
}
else if (Input.GetKey(KeyCode.D))
{
myRigidBody.velocity = Vector2.right;
}
else
{
if (movementJustStopped) { myRigidBody.velocity = Vector2.zero; movementJustStopped = false; }
}
myRigidBody.velocity *= movementSpeed;
i'm sure it can be easily refactored, but that's not my priority at this moment
😮
what?
that else if chain 😂
this can be a few lines by using Input.GetAxis("Horizontal") / Input.GetAxis("Vertical")
i know lmao theres definitely a better way to go about it
i didn't know about that method hold up
ima try it
I don't see anything that would prevent velocity change during knockback
I would do a bool set true in the coroutine on the first line, then set false on the last
If it is true, don't set velocity
alright
actually one problem, the code for the knockback is in a preset
so it would be hard to access from another script
better get used to it
so what is the prefab, like the object causing the knockback?
the prefab is an enemy sprite, and it controls the knockback
i could dedicate a gameobject for it though
so just put the knockback logic on a public method on the player
have this collision logic call it
alright, will do
way easier then needing movement code needing to check stuff on enemies
btw are you doing like topdown?
yeah
void Update()
{
inputs.x = Input.GetAxisRaw("Horizontal") * Time.deltaTime;
inputs.y = Input.GetAxisRaw("Vertical") * Time.deltaTime;
inputs.Normalize();
}
Vector2 inputs;
private void FixedUpdate()
{
var moveDir = transform.TransformDirection(inputs);
rb.velocity = moveDir;
}```
Your whole code
thought you could do edit vectors in place like that unless local
but same idea just construct it with
inputs = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
ohhh
i did exclude some of the code that deals with animators, but it does use a blend tree so i can work with this
yeah you're right, im used to having separation of my movement code vs my animation code
thats probably the smarter thing to do lmao
looks cleaner too
yeah my animation logic generally just checks stuff like velocity and makes decisions based on that
often will drive the x and y speed into the animator to drive blend trees
thats pretty much how mine works
or Invoke something else like events, if needed like grounded states etc
so its not a problem
for sure yeah
alright, you guys just gave me a ton of homework so i'll get back to you and tell you if this solves my initial problem, thanks!
yes its tricky your problem because .velocity will override any Force you applied during impulse as soon as it kicks back in
you could also mitigate it by using velocity instead, by just adding to current velocity and clamp or assign it
either way I'd learn how to use a coroutine for a timed event like that
wait in the code you provided for movement, does TransformDirection look choppy? or does it have the same effect velocity would?
its choppy?
all that is doing is converting from local to worldspace
i haven't tried it yet
Also forgot to write * moveSpeed lol
its prob too slow
rb.velocity = moveDir * moveSpeed;
oh wait sorry my eyes glazed over that last line
if its choppy maybe something else is wrong?
i thought you weren't changing velocity and instead using a different method of movement
mb
i'm tired lmao
if you come back to it after a break or a sleep, it will all be clearer
ahh ok . and onestly for 2D topdown you prob dont even need the TransformDirection too
lol Im used to 3D
all good
yeah chances are the transform direction is doing nothing
unless the parent of the player is rotated on the z
i unfortunately can't sleep right now because i'm sick but i am looking forward to getting rest and being able to think straight
i'm curious, why did you put the velocity in fixedupdate rather than update?
physics objects should ideally be moved in FixedUpdate (this is the physics loop)
although I heard even in update they wait until physics loop anyways so 🤷♂️
I just know its good practice
dontforget for that you need time.deltaTime
inputs.x = Input.GetAxisRaw("Horizontal") * Time.deltaTime ;
inputs.y = Input.GetAxisRaw("Vertical") * Time.deltaTime;
inputs.Normalize();```
right.
movement feels fine, I'm getting an error with the knockbackTimer though
Coroutine 'knockbackTimer' couldn't be started!
UnityEngine.MonoBehaviour:StartCoroutine (string)
slime:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/slime.cs:106)
show the code
(in player script)
public IEnumerator knockbackTimer()
{
knockbackActive = true;
yield return new WaitForSeconds(knockbackDuration);
myRigidBody.velocity = Vector2.zero;
knockbackActive = false;
}
(in enemy script)
if (!collisionCompleted)
{
playerRigidbody.velocity = Vector2.zero;
playerDirection = (player.transform.position - transform.position);
playerRigidbody.AddForce((playerDirection * playerKnockback).normalized, ForceMode2D.Impulse);
damageSFX.pitch = Random.Range(1, 2) + Random.value;
damageSFX.Play();
logic.updateHealth(-damage);
collisionCompleted = true;
StartCoroutine("knockbackTimer");
}
ignore all the extra stuff I forgot to filter it out
you cant call it on a different script like that
like a field in the inspector
[SerializeField] PlayerScript playerScript
playerScript.Something
also you want the enemy to be knocked ?
not sure why its in the enemy
i originally had it so that the player had a normal collider and the enemy had a trigger collider
so to not have an extra collider i put the code with the enemy instead
so in the OnTriggerEnter of that enemy just get the component of knockback and call that
or dont u have a damage reciever type script , that would be best
i already have the player gameObject referenced in the enemy code, so its not a problem, it would just be extra work to rework it
alr
not much would change so far, you'd still need to disable the movement .velocity overriding
i did
btw Random.Range(1, 2) this will only ever give you 1
oh wait its using the float version nvm
why wouldn't it work with int?
No you are right. He will only get 1.
integer is not max Inclusive
that's a weird decision
it seems to work fine though so i'm not worried about it
I think its using the float version because .pitch is a float and they're doing + another float
Well you are getting 1 + Random.value every time. So it will work.
You can change that code like this if you want that;
pitch = Random.value+1;
No its not. He must spesifiy the type with "f" in the function itself.
damageSFX.pitch = Random.Range(1f, 2f) + Random.value;
This is the correct version.
yes you are correct
It will stay integer.
whatever, i'm happy with how it sounds so I dont need a broader range than just 1
idk why i second guessed myself lol
thats because its always 1 + 0 to 1
You are literally don't wanna say that you are wrong.
Your code literally does 1+Random.value. You must fix your code. Or remove the random.range call.
You can't be happy with that code.
damageSFX.pitch = 1 + Random.value;
happy now?
saved yourself a call into the same class twice 😛
Yes this is the same as;
damageSFX.pitch = Random.Range(1, 2) + Random.value;
this.
Now its more performant as well.
not that much here, but over time things can add up
ofc yeah
ok so new problem: no matter what i set playerKnocback to it knocks back the same distance
ur normalizing the whole thing after
ofc it has no effect
right i added in the .normalized to try and fix the original problem, forgot to delete it
alright, I think its finally functional!
thanks to everybody who helped
Lmfao, just coming back. Perfect timing haha!
Nice work
how do i add or remove a function to the IAP button through script?
public CodelessIAPButton PowerUpButton => _powerUpButton;
PowerUpButton.onPurchaseComplete.AddListener(AddPlayerSpeed);// this ist working
This is a code channel and this isn't a code question. Those usually can't be selected because they're already in the project with no changes.
Why do VectorXInts have a Clamp method but VectorXs don't?
Because whoever added the Clamp method to Vector3Int didn't add it to Vector3.
well, that's an unsatisfying answer. aight then.
Is there a better way than GetComponent to get information from an colliding object (with OnCollisionStay2D)?
is there a clean/built-in way to go from Vector2 to Vector3 with a specified z, or do you just have to set it afterwards or manually new Vector3(v2.x, v2.y, z)?
you can make your own extension method
yeah, but i'm asking if there's a built-in way
there isnt
just asking out of curiosity, not need
Just wanna make sure this didn't get drowned.
depends on what kind of information do you want to get
An Int
from a component?
I have a viewcone. And I want it to detect if whatever is entering it is hostile or not by getting its TeamID
Yes
well then you have to get a reference to that class
then to that int
so there is no other way
than using GetComponent
Yeah, but is there a diffrent way, than using a class?
you can use TryGetComponent to avoid 2x GetComponent call
what exactly are you trying to achieve
detect who is enetering your "viewcone"?
there is no built-in sensor or anything like that
I want not use getcomponent every frame
then cache it just once
you dont need to ues get component everyframe, that is a veyr bad idea
Indeed
you'd need to show the code
{
if (!IsHost) { return; }
if (TeamManager.CheckForHostile(teamSelector.GetTeam(), trigger.GetComponent<TeamSelector>().GetTeam().id))
{
fire = true;
}
}```
im not sure why are you checking for all that
in OnTriggerStay
when you just want to detect who ENTERED the viewcone
Well, if I use enter and exit. And 2 things entered the cone. It will stop shooting if one leaves and one stays
you should have a list
of objects that are inside the view cone
and add/remove them in enter/exit
and set fire to true
if there is atleast 1 in the viewcone
How do I know which is which?
well you have the teamid
dont you
2 lists, one for allies, one for hostiles
in OnTriggerEnter
check if its ally or hostile
and add it to ally or hostile list
then you can check allies.Count or hostiles.Count etc
and in exit
check if its ally or hostile
and remove it from the list
as simple as that
Coulnd I just make an int instead that counts how many there are? Why do I need a list?
lol k
- In renderparams struct, what's the difference between the
layerandrendaringLayerMaskproperties? One beingint, the latter beinguintand that's it?
renderingLayerMask is a separate mask that masks based on Renderer.renderingLayerMask. Instead of culling based on GameObject layers, you can additionally cull based on Renderer.renderingLayerMask. This means you effectively have 32 additional layers you can use for rendering. Another nice thing about these layers is that each Renderer stores a mask instead of a layer index, so each Renderer can have multiple layers.
- I see. So
layeris mandatory andrenderingLayerMaskis optional?
Both are always used. In this case, you are deciding what GameObject layer and what renderingLayerMask this draw call will use, so it can be culled correctly.
i disabled sword -> player collision in the matrix but the sword still wont collide with the wall
Ask yourself what happens if layer == 6 ?
wat
what I said, read your code
How to fix this specifiq lighting issue? I tried enabling Stich Seams but with no luck.
0 is also a layer
what has that to do with your code?
Were to put it then
the 7th layer is the wall so...
sorry, that wasn't for you. you would be better in #archived-lighting
Oh i see, perfect!
read your code!
just tell me what's wrong dumbass
<@&502884371011731486>
wtf im asking you what the problem is and you dont tell mee
really? you just got yourself blocked, good luck
huuh
😳
Move on if you can't control yourself.
i posted it cause i wanted help and hes not helping..
Don't whine please
idk what i have to read and hes not telling me
Nobody has to tell you anything, really. You're not owed anything here.
how is saying read your code helpful
no one here is paid to help people, its generally just people doing it on their free time
what is there to read
You learn the skill of reviewing your code and finding the error yourself
he made it seem like there's something wrong with this code
when there isn't
there is
then what
assuming you dont want the first and last case executing when its layer 6
there noting wrong with the layers cause even the else doesn't get called
then check to make sure the collision matrix actually allows this things to collide in the first place
and also put a log at the start of the function to find out if its calling when you expect it too
Debug.Log() the collider to check what layer has been triggered
talking about the character
OOooooh
would need both a rigidbody and a collider marked as a trigger
Yes!
good trick: debug log everywhere in your code so you knows where it didn't trigger
Debug.Log(collider.transform.gameObject.layer);
Then you can see what layer actually hit. Then you will see that your number 6&7 are good or not
that
OnCollisionEnter only works for a dynamic Rigidbody interacting with something. This really doesn't look like the sword is a dynamic Rigidbody
Also yes your code is faulty with regard to the if/else logic
You can also take a look at OnTriggerEnter instead of OnCollisionEnter. Make your collider a trigger and use OnTriggerEnter
on triggerenter doesn't work either
You need to have everything set up correctly for either of these to work
Show what components are on the objects
It seems like you're just kind of guessing right now
@orchid abyss This is what? It's disabled
it gets enabled with animation event
Is there a RB on the sword?
Just a collider is not enough
na
Then the callbacks will not run
then collision is forwarded to the next RB in the parent hierarchy
oh really
A Rigidbody is required
its one of the first lines in the docs for the trigger messages
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
Note: Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.
now the sword appears in the hand for a second then disappears
how can I get rid of these weird ghost tiles? (The Dirt and the Metal Block)
I can't click on them
Are Triggers or Raycast better performance wise? (for detecting enemies)
correction: adding stuff is like hunting for the right place to add one line of code and then realizing that it's actually going to be much more than one line of code, oops...
you often want both, where a trigger makes sense for 'enemies nearby' but often you also need stuff like 'enemy line of sight' which would require some rays
Hm. Prop makes sense. Tho I would like to know eighter way. Because I have a lot of stuff walking around
Can someone give me a example of how to convert reflection.MethodInfo to unityevent, I just couldn't get it to work thanks in advance
I'm working on a project folder setup wizard and I like to use InputSystem so I have an inputsystem asset in the package that I can copy to my assets folder using AssetDatabase but cannot delete the original files so that they do not conflict with eachother, I have tried the MoveAsset function and it didn't work, what do I do to move/delete files in the packages folder
AssetDatabase.DeleteAsset("Packages/com.5babbittgames.babbitts-custom-tools/Runtime/Input/GameInput.inputactions");```
So if you somehow encounter this same problem, a workaround I just found is simply renaming the destination asset name
AssetDatabase.CopyAsset("Packages/com.5babbittgames.babbitts-custom-tools/Runtime/Input/GameInput.inputactions", path + "/NEWGameInput.inputactions");
For example setting the inputactions asset to NEWGameInput.inputactions this will not get rid of the one in the original package folder but you can just use the new name in any references to the input asset, though this may still lead to headaches of missing references for the initial project
I still hope there is a way to just cut and paste from the packages folder to the assets folder with script
it worked! i had to add rigidbody to the sword and add constraints
😆
Anyone know how to make grouped/categorized enums for long sets of enums? Used to be able to do something like this using [InspectorName()] but doesn't appear to be working after upgrading to 2023.
{
[InspectorName("Category A/A1")]
A1,
[InspectorName("Category A/A2")]
A2,
[InspectorName("Category B/B1")]
B1,
[InspectorName("Category B/B2")]
B2,
}```
Anyone be able to tell me which one is the accurate one?
why do they go out of sync after a while ?
private void Start()
{
StartCoroutine(TimerRoutine());
Application.targetFrameRate = 7;
}
private void Update()
{
totalSecondsII += Time.deltaTime;
}
private IEnumerator TimerRoutine()
{
while(true)
{
yield return new WaitForSecondsRealtime(1);
totalSeconds++;
}
}```
the coroutine resumes on the next frame after waiting for 1 escond
it doesn't instantly execute the moment 1 second passes
TimerRoutine will end on the first frame after one second has passed. Therefore, it will always tend towards overshooting 1 second by a value of at least 1 frame
Ohhh I see, so the better accurate time is the one in Update ?
it's the way I'd do it
note that the two techniques are measuring different things
WaitForSecondsRealtime ignores the timescale
Yeah that's good for me, I'm working on a simulator game, wanted a somewhat accurate timer
I will use Update then !
thanks @heady iris & @naive swallow
Is there a function to check for equality on all components of a vector?
Could someone help me with an error I just started with unity and haven’t seen it before it’s “TextureImporterInspector.OnlnspectorGUI must call ApplyRevertGUI to avoid unexpected behaviour. UnityEditor.TextureImporterInspector:OnDisable()” I don’t understand what that means yet lol
==
Yeah i can manually check each component but just wanted to know if there was a built in function for that
What do you mean each component?
There is. ==
aVector == anotherVector
x, y and z
Vector1 == Vector2
i wanna know if x == y == z
Ah, okay, that you have to do manually
That is not what it sounded like you were asking haha
Can I ask why you want that? Grid system?
Well, you could do some math, like (someVector / someVector.x) == Vector3.one but that's probably worse
This is something wrong on Unity's side. Never seen it before myself.
Does it persist after restarting the editor?
Umm I’m not sure
I'm making a component with NaughtyAttributes for button effects. The scale effect has 2 modes, one uniform and the other where you can choose each value. I don't even remember what i wanted that for lol
It had something to do with the Uniform Scale option
I think i wanted to convert one into the other
if possible
Hi. I have a problem with the interactive parts on my sail ship model.
My ship is fully fitted with primitive and convex colliders. It also has cannons, they are all set up with their own animations and Cannon Controller Script.
I want the player to be able to walk around on deck, and when he looks at a cannon, he should be able to call the FireCannon() Function in it's Cannon Controller.
So i wrote a script that projects a Raycast from the camera. At first it didn't work. The RaycastHit only found the colliders the cannons are made of. When i added a box collider as a trigger around the whole cannon and put it on the parent object, it worked! The Raycast found the trigger collider, identified it as cannon by it's tag, was able to find the Cannon Controller Script and call FireCannon().
Then i added a Rigidbody to the whole ship (the reason i crafted that convex collider setup in the first place). And now the Raycast can't find the Trigger Boxes anymore. All it finds is the big compound collider of the ship.
I think i maybe have the complete wrong approach to this problem. Can somebody help me?
You can use a layermask for the raycast and have the canons to all be on one layer so that your raycast only finds the canons
or you could change the ships layer to a built in unity one called "Ignore Raycast"
The raycast gives you the collider you hit.
https://docs.unity3d.com/ScriptReference/RaycastHit-transform.html <-- rigidbody's transform, if there is a rigidbody; otherwise, it's the collider's transform
https://docs.unity3d.com/ScriptReference/RaycastHit-rigidbody.html <-- rigidbody, if there is one
https://docs.unity3d.com/ScriptReference/RaycastHit-collider.html <-- collider you hit
Sounds like you just need to grab the collider
if (!hit.collider.TryGetComponent(out CannonController controller))
return;
controller.FireCannon();
this uses TryGetComponent to look for a CannonController
it bails out if it fails to find one
Does the .transform, rigidbody and collider do a GetComponent under the hood?
Collider I imagine no since we needed to get that to do the collision, but rigidbody?
I dunno. I guess we could consult the C# reference
public Collider collider { get { return Object.FindObjectFromInstanceID(m_Collider) as Collider; } }
it sure does something!
yeah, these are all properties
Uh huh...
A lot of Unity classes and structs either call native code or need to be accessible from native code
So they can get funky
Well it's tossing an int as an ID in there, so it's probably some dictionary lookup?
Note that none of this should really matter to you
Uh akshully 🤓
Hi! Does anyone know how to get all scores from a bucket leaderbord in js unity cloud?
I use const getScoresResult = await leaderboardsApi.getLeaderboardScores(projectId, "LDBBucket"); and the result: "detail": "Score submission required to view the scores of this leaderboard",
@ocean nova Thank you. I tried it out just now. It worked so far as my Debug is now only finding the cannons. But as soon as the Rigidbody is on the ship it still only finds the the ship's compund collider, and can't find the trigger box on the cannons.
@heady iris Yes, i thought it would be as simple as grabbing the collider. But all it grabs is the compound collider that is generated by the ship's Rigidbody. The cannons are also part of the ship's hierarchy, so i think the Trigger Boxes are merged into the compound collider. And putting them on a different layer doesn't prevent it.
Hello, my android build doesnt call OnApplicationQuit when i close app, but if i change it to OnApplicationFocus, its calling but now it wont work in editor now. What should i do?
I'm trying to set up an fps multiplayer game, and i have the strangest bug here where on trigger stay or enter simply doesnt get called unless it hits a player (you can see at the bottom a Debug,Log for when the rocket initially spawns and hits the player, but nothing is printed when it hits the wall for example)
I'm not aware of "compound colliders" outside of the Unity Physics package.
what do you get if you log hit.collider ?
I should say that I'm not aware of the colliders actually "merging"
The individual colliders continue to exist
So, all of my ship, even the cannons, are all childs of the "Sailship" Object, which actually has no Collider on it. But "Sailship"'s childs do have colliders.
My hit.collider is now picking up all the childs with their colliders, like "railing_col" and "cannon_wheel_col.
But as soon as i put a rigidbody component on the "Sailship" Object, the same Raycast only can find the "Sailship" Collider. I still can look at the wheels of the cannon, but it only knows this collider as "Sailship" Collider. So in my understanding the Rigidbody merged all of the colliders of the childs into one big one.
And my problem is, one of the colliders on the cannon was a trigger which i used for the Raycast to find the cannon object. And now, with the Rigidbody on the "Sailship", even this Trigger Box can't be identified. It's all "Sailship" Collider.
I'm searching for a way to prevent the Trigger Box to get merged or another approach to make my cannon useable when looking at it.
I do not observe this behavior.
Cube has a trigger collider on it. Rigidbody Test has a (kinematic) rigidbody on it.
A raycast finds the Cube collider, the Rigidbody Test transform, and the Rigidbody Test rigidbody
Show me your raycasting code.
`public class Interact : MonoBehaviour
{
public Transform other;
LayerMask mask;
void Start()
{
mask = LayerMask.GetMask("Interactive");
}
// Update is called once per frame
void FixedUpdate()
{
Physics.Raycast(transform.position, transform.forward, out RaycastHit hit,10, mask);
other = hit.transform;
if (other.CompareTag("Cannon"))
{
other.GetComponent<CannonController>().FireCannon();
}
}
}`
This is not checking hit.collider at all.
You're getting hit.transform
I said to use hit.collider beacuse that gives you the actual collider you hit
Do that and it'll work fine.
other = hit.collider
Read the docs on RaycastHit.collider vs .transforn
(:
They do different things
You should also use the bool value Raycast returns, to know whether it hit anything
I forget if you get a null RaycastHit back
or if you just get one with junk data
the latter would be particularly problematic
wait, it's a struct, innit
It's a struct, so default values
RaycastHit is a struct
yes, definitely
also like the way code flows with it returning a bool anyways
hit.transform will most likely be null, which will throw an exception if you try to access anything on it
It works!!! Thank you very very much!
Somehow I thought, the Raycast is only able to find colliders and the hit.transform is a shortcut to get to the object the collider is on!
Thanks everybody!
I have some ships to battle, hooray!
is it bad idea to detect pressed or interacted ui elements in a canvas by raycasting with eventsystem? I don't want to use IPointer_xxx interfaces for it (for now)
Can someone help me with this script? im making a fnaf styled camera controller and ive benn trying to make the camera go where the cursor is. But it's not working no matter what i do, can someone pls help? 😭
public class CameraController : MonoBehaviour
{
public float rotationSpeed = 5f;
public float maxVerticalAngle = 30f;
public float maxHorizontalAngle = 60f;
public float smoothTime = 0.12f;
private float pitch = 0f;
private float yaw = 0f;
private Vector2 rotationVelocity;
void Update()
{
yaw += Input.GetAxis("Mouse X") * rotationSpeed;
pitch -= Input.GetAxis("Mouse Y") * rotationSpeed;
pitch = Mathf.Clamp(pitch, -maxVerticalAngle, maxVerticalAngle);
yaw = Mathf.Clamp(yaw, -maxHorizontalAngle, maxHorizontalAngle);
float smoothPitch = Mathf.SmoothDampAngle(transform.eulerAngles.x, pitch, ref rotationVelocity.x, smoothTime);
float smoothYaw = Mathf.SmoothDampAngle(transform.eulerAngles.y, yaw, ref rotationVelocity.y, smoothTime);
transform.rotation = Quaternion.Euler(smoothPitch, smoothYaw, 0f);
}
}```
I did this a while ago it was fun
let me see how I did it
alright
also can you record a vid, what you mean by not working
It feels like an fps camera, and i want to feel like a fnaf one, so it rotates towards the cursor position on screen
yk?
it barely rotates
also the original has no pitch
Yea im not very good at math
not really lot of math needed , just remove the pitch stuff for starters if you want the original
I mean i want it to be able to look up and down
I just want so the camera rotates towards the cursor, like in fnaf
the origina fnaf the camera doesn't rotate towards cursor
Wym? it does
How does fnaf camera work, I checked a clip and it seems that it rotates when your cursor is on the edge of the screen?
you could do it in unity as a slight clamped rotation
but original you can tell its shifting pos
You should just check if your cursor is on the left or right side of the screen and then rotate at a constant rate
yup had the same thing, wish i could find the project
And top/bottom if you want that
I made "Hot Zones"
Ok ok ok thx i'll try to do that
depending on Screen.Size
Did something like this, i think it looks good (also kinda like scp-079 in scp:sl lol)
if it works for your game go for it
What's the advantage of creating parallaxing backgrounds with a non-orthographic camera?
I was doing some searching and found that hollow knight had done theirs this way, in 3d rather than 2
perspective
as you move towards the side, you are seeing it from a slightly different angle
vs with ortho you are always seeing the backgrounds from the exact same angle
riiiight
hollow knight also does some other trickery too, they have multiple things stacked, so you see more stuff behind the first item as it reaches the edge of the screen due to the camera perspective
has a mix of camera types in use for backgrounds, forgrounds and the gameplay layer
How do I change the variable of a clone? Here's the code: https://pastecode.io/s/xp91ias7
waht do you mean by clone?
a prefab asset or instantiated prefab
I think the second one
when you call instantiate it returns the instance, you can use that to access it and call methods or modify it
Huh?
public PuyoScript _prefab;
private void Start()
{
var inst = Instantiate(_prefab);
inst.dropSet = 5;
}
That's javascript, not C#
you do know that var exists in other languages besides just javascript, right? and in c# it is used for an implicitly typed local variable
also method signature is totally wrong for js
wow where did you read this information? I'd like to take a look at it too if possible
Just to learn a bit more about cameras and parallax implementations
That's some visual trickery I wouldn't have thought of
observations and a bit of ripping thigns apart to see how it ticks
I guess they did have a really good reason to use 3d
Here you go https://hastebin.com/share/nutahopeqo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What lol, that is not javascript. Nor is what javascript looks like
well when you are already in a engine that lets you easily mix 3d and 2d why not just do what ever gets the look you want
that's true
i swear everytime they post code, its always this one exact script that hasnt changed
I didn't even know there wasn't really a difference between project settings for 3 and 2d till today in editor(camera)
I did notice SOME changes, but not even close to enough.
yeah they mostly just effect how the editor behaves by default and sorting though
Going through and just adding curly braces and whitespace only does so much when it's a minefield of redundant if statements
It feels harder to place 2d sprites in 3d editor if that makes sense
But nothings stopping you from using both I'd imagine
it can me, depending on the type of game you are making the grid snapping, or tilemap help
By the way, any recommended guides or articles about ui placement and management in unity?
I've been googling but I figured why not ask people who've done it before as well
