#archived-code-general
1 messages · Page 208 of 1
you probably don't want spread to be in actual units ig but the point still applies
I stink at this stuff unless I'm working on* it, but you have the direction from your camera, so you just need to multiply it by a rotation of the spreadvalue, right
i just would like to make sure the ray comes out at the exact same angle as the bullets otherwise it will really frustrate the player
Why not just use playerCamera.forward+ someDisplacementVector?
Actually nvm.
You should rotate the camera forward by some random rotation
it... apears to be working
this statement, that is Vector3 direction = (Quaternion.Euler(playerCamera.eulerAngles + spreadValue) * Vector3.forward).normalized;
It would work. It's just not as intuitive for me as what I suggested.
i like it because it means if i decide to change the algorithm for the spawn rotation of the projectile objects i can change it in the same way on the raycast
ok i got a nice dropdown working fine, but i have a question, if in unity I have a dropdown with 50 options, can I click on one, it detects the letters I type and go to the option that contains those letters using the play mode? like in the unity editor? because in play mode doing scroll in a really big list its hard >.<
Anything is possible if you want to script it in
They're both OOP languages, so there are a lot of similarities. But, other than syntax, you'll have a different range of methods provided by the languages.
they used to be more similar but developed in pretty different directions over the years, they each have some features the other doesn't
this is more or less what I want to be doing if I want a function with an optional out, right?
public bool TryGetTile(PuzzleManager.Direction direction, int distance, out Tile returnTile, Vector3Int offset = default)
{
if (puzzleManager != null && puzzleManager.TryGetTile(tilePosition + offset, direction, distance, out Tile outTile) == true)
returnTile = outTile;
else
returnTile = null;
return (returnTile);
}
public bool TryGetTile(PuzzleManager.Direction direction, int distance, Vector3Int offset = default)
{
return (TryGetTile(direction, distance, out Tile _));
}
or is it better practice to have a different specified function
haha kinda looking like my voxel tool
😛 I'd imagine i'm walking on a very treaded on path. been fun so far
A lot of things. They are similar sure, but it's like asking what's the difference between Spanish and Portuguese.
i will just return the object since there is a unique value that indicates "failure"
the null
Yeah, if you want to return a bool and a value, that's a good use of out instead of checking for nulls
if((something=GetComponent<Something>())!=null){
work.
}
```c-way
btw if there is no unique value indicates failure then i will use try pattern
eg a method that returns all possible int value
This hurts my soul
I'm having a brain fart moment. So I'm making this Objective system. Each objective is comprised of a list of tasks that need to be completed in order. The tasks themselves dont have progress like kill 10 boars they are just player did action A for example. Both tasks and objectives are Scriptable objects. Now I have everything working with a event system. Meaning I can invoke a TaskCompletedEvent that holds a Task inside it and the Objective manager checks if that is the currently expected task to do and does its job. But how do I invoke the even based on user action in a nice way? For example I know that when he clicks on a specific object that would count task A as being completed. I dont want to reference the task SO's all over the place. Perhaps my design is bad.
Sounds like you should have a general Task manager. Perhaps each task should be bound under a specific key, such as "Task_Fetch_Bread" which can then be looked for in this manager?
Or an id, but then you would need to know the id so a static identification might be better
ah yes I can have a Dict of all Tasks on a manager
Is possible to check if user click on the drop-down and then pass to a method what drop-down is, in update method then check what keys are pressed and then search inside options of this drop-down if any option name starts with this sequence ?
Sounds doable
You're not just limited to what's shown on the inspector. You can use the values such as the length of the scroll, and the current position through scripts to use.
Sorry I failed to reply since I saw no notification.
I have items in an Overlay Inventory and want to be able to inspect them in 3D. I need some UI elements like background to display behind the 3D Objects that is being manipulated/rotated around.
Therefore, I need my UI to become Screen Space - Camera. Thing is, I'm now trying out simply having another Canvas for this specifically without changing the entire UI.
Do you have a recommendation for how you'd approach the issue? Thanks a lot!
By passing the string the user type ? I don’t understand
https://docs.unity3d.com/2018.4/Documentation/ScriptReference/UI.Dropdown.html
Take a look through all the methods
also the interfaces it implements:
https://i.imgur.com/bB0SRzX.png
Make a script and throw it on the same GO as the dropdown component
so i'm seeing huge reliability issues now that i've switched my game to raycast detection instead of collision based detection, it seems like it randomly misses moving targets with more than a 50% rate, even when they're moving directly towards the player.
for reference the target that i see the failures on is a set of colliders and rigidbodies made with the ragdol creator controlled by a navmeshagent and animator
is gameobject.getcomponent faster than transform.getcomponent ?
thanks! i will check it
None of the two. GetComponent() directly would be faster.
Though, the compiler would probably online it anyway.🤔
i think the getcomponent finally calls go.getXXX?
The compiler can't inline access through a component or gameobject
Both Component and GameObject GetComponent<T> have their own "GetComponentFastPath"
so don't think about it
I've got this pretty basic charactercontroller based movement function but when it's actively being used and i rotate my planet my sheep get tossed around. online theres a lot of suggestions to deal with charactercontroller jitter and other related stuff but any suggestions on how to account for this missing movement?
is the camera moving or is the entire world?
world
Guys I broke my project using github, so I did what I was doing since the time I made this project to do version control using github desktop. And today after I pushed the commits, I got error in unity "merge marker conflict" and I tried to remove the markers from script but my whole scene is now gone and have the same error idk what to do, I tried pulling the stable version just before this but now my game have errors which weren't there before, everything got messed up please if anyone can help I would really appreciate
I could, but we're gonna have to do this in private message because we might flood this chat
Send me a PM if you want my help
@jolly stratus Probably better if I tag you
here is a great screengrab of the raycast failure, the debug rays are not drawn all the way out, the actual rays are 100 units long, but it goes straight through the colliders of the enemy into the ground 198/200 times during this test
@royal temple alrighty
i even changed the code for the raycast to execute at the next FixedUpdate instead of immediately to garauntee that the object locations are all accurate when the raycast happens, no dice, even with the enemy standing still doing idle animation it's incredibly inconsistent
I have a SO. Each instance of the SO should hold a reference to a different class for runtime instantiation. E.g. SO is "WeaponInfo", the instance could be for a blaster, and should contain a reference, serializable in the editor, to the BlasterRuntime class.
Is there a better way than serializing a string and wrapping the cast to type?
however the moment the navmeshcontroller and animator are disabled all the raycasts go from a 15-30% success rate to a 100% success rate, so it has to be something to do with the animator or the navmeshcontroller
Show code?
Also you can use Physics.SyncTransforms() rather than waiting for FixedUpdate
I'm at the point of tinfoil hat wearing so i thought i might as well try fixedupdate, nothing seems to work and the debug.drawray are clearly going directly through the colliders. But when the enemy is "alive"(animator and scripts are enabled) it goes from a 100% success rate to 30% at best despite projecting the ray from a consistent location
Which collider (s) in particular are you expecting to hit?
I think we had a similar problem and fixed it by changind the update mode on the animator to fixed
the colliders shown in the photo is what i'm expecting to hit, capsule and box colliders that are attached to bones of the enemy with rigidbodies attached, the large capsule collider is layermasked out and is not causing the issue
i don't know what you mean by update mode to fixed, but i found that the animator has a mode called "animate physics" and turning that on seems to have fixed the issue at least mostly
always something simple
Its probably from the dif versions our proj is on 2023
Anyone know if there's an easy way to sign in through existing microsoft account details in unity?
In other words you just enter your email and password and it checks if the details match an account
Do you guys know if monobehaviors are executed in parallel ? Like is it better to have a list of class instances where on every update you call the "update" method individually on every instance in the list, or is it better to instantiate objects with these classes and make them inherit from monobehavior so they can call it in their own update function?
if you dont use monobehaviour some things wont work
unless you have a reason not to, use the built in update
but is it more ressource intensive to have update loops running on instantiated monobehaviors rather then just remotely calling an update function in a class?
i dont need to have the transforms and all i just need a function that gets updated every frame
the entire point of classes is they are self contained for the most part
use built in updates
if you have thousands of things to update and don't need them to be monobehaviours for any other reason,it can save memory/instantiation costs to make your own non-monobehavior class and update them manually (in theory this kind of problem is what ECS systems are for)
but that defeats the purpose of object oriented programming
for most cases you should just use Update()
well yeah, OOP isn't the only way to write code, ECS is data oriented
i know but if your gonna code a whole update system why not just use direct x and make your own engine?
Ok so basically this is my structure, PlayerShooting can either instantiate a GameObject with a ShellHandler monobehavior on it, and each shell will then run their update loop while they are allive OR PlayerShooting can make a new instance of a class and add it to a list and then on update iterate over every "ShellHandler" and call ShellHandler.Update
just use monobehaviour for something liike that
but could you not just call on collision enter when it hits?
and fixed update to move the bullet
that's a pretty bizarre leap, unity themselves added an ECS system because monobehaviours are inefficient in a lot of cases
eitherway for his use case monobehaviour is fine is it not?
No because a "Shell" in my game is made of "Projectiles" that need to be monobehaviors because they need those collision, and Transform components, but they are also made of Modfiers that don't need monobehaviors, they just have an effect on the instantiated projectiles while they are alive, meaning ShellHandler is only used to keep track of the projectiles and execute the instructions on every part of that shell in order
im confused what exactly does the shell handler do?
For example "Part" can have an "Init" method that is called when a shot is fired, and for projectile.init it may be instantiating a bullet, but for modifier.init it might be applying a speed modifier to the projectile it is linked to, one shell handler has multiple projectiles and modifiers attached, and it needs to call the update function on the projectiles and Modifiers
every shot has a shell handler associated with it
This sounds like you should be using ScriptableObjects for the modifiers
So basically like a coroutine manager for a single shot
i'm already doing that
projectile and modifier are inheriting from part which is a scriptable object
only shell handler and player shooting are monobehaviors
I have like a static update manager for projectiles like this because stuff like multiple projectiles need some extra logic to fan out, or to be dispersed through some time interval
hmmmmm yeah kind of
is making coroutines for each shot expensive ,
?
Eh, some overhead I would presume, though I don't see anything wrong if it's all contained in a single update loop if you can manage that.
well it would just look like: for every ShellHandler in InstantiatedShells : ShellHandler.Update();
even then, probably not that big of a problem for multiple different GOs to run the update
Take care using this system
what are the physics implications of making a class that derives from Collider2D?
why are you saying that ?
physics and colliders aren't inclusive to each other
I want to make DuplexCollider2D : Collider2D. It takes in one Collider2D; makes a duplicate Collider2D on the same gameobject, and sets some settings to be different between them so they can be decoupled
but idk if having a DuplexCollider2D component would confuse the physics system into asking it for contacts etc
Do you need to derive from it though
I am not exactly sure
most of my code acts on collider2D, and takes collider2D to work on things.
It kind of functions as a composite collider, in a way
Perhaps some script that just takes in all colliders from the GO and work with that
GO?
gameobject
I’ll see if I can do something like that
another question on implementation
some of the colliders to duplicate are compositecollider2D, tied to a tilemapCollider2D, and I fear that shit will get expensive
a saving grace is that those specific tilemap colliders are completely connected. No little islands.
Do you think I could take in a compositecollider2D, and make a polygonCollider2D out of it?
one that matches it perfectly?
Haven't looked into polygon colliders, but the issue of trying to bake these colliders into more performative types is something I'm actually researching right now
developing something similar to the tilemap and one thing I'm trying to tackle is removing the colliders per tile and instead baking it all together if possible
rather, the 2D tilemap is probably one large collider and uses world point relative to the map pivot to get the index, but dealing with 3D makes that a little more complicated
CompositeCollider2D normally bakes a tilemap collider into a small set of polygons
Ah, makes sense. I should probably play around with it to get an idea how unity optimizes it all out of the editor.
We've tried asking there, myst1ck is my friend...
Okay, so this editor script, called ModelGeneratorEditor, is supposed to control ModelGenerator component:
The functions that update the values of the ModelGenerator are in the OnInspectorGUI. This function as it suggests, is called when values are changed in the inspector....
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawDefaultInspector();
ChangeGenerationWay();
EditorGUILayout.LabelField("");
CreateRoomSettings();
CheckModel();
if (GUI.changed)
{
EditorPrefs.SetInt("RoomTypeFlags", roomTypesFlags);
EditorPrefs.SetInt("SquareRoomsFlags", squareRoomsFlags);
EditorPrefs.SetInt("RandomRoomsFlags", randomRoomsFlags);
EditorPrefs.SetInt("RotationWay", rotationWay);
}
serializedObject.ApplyModifiedProperties();
}
In CreateRoomSettings for example, I am updating properties of ModelGenerator.
I should obtain the ModelGenerator reference in OnEnable:
void OnEnable()
private ModelGenerator modelGenerator;
{
...
modelGenerator = (ModelGenerator)target;
...
}
but what im suspecting is that this "target" is not the same one in the editor, but rather the one that's loaded dynamically with the scene...
I've also tried calling OnInspectorGUI in OnEnabled.
But it seems that the Editor functions don't work, such as DrawDefaultInspector, since again the scene in which this editor script is "Enabled" (since it's target script is enabled), is loaded dynamically
woudln't you Want OnValidate instead of OnInspectorGUI?
this just says
Implement this function to make a custom inspector.
Inside this function you can add your own custom IMGUI based GUI for the inspector of a specific object class.
Note: This function has to be overridden in order to work.
I am stuck and I don't have my project saved...
Is there any way I can save my project before going to task manager to terminate unity?
I don't want to lose my progress
Or maybe cancel Reloading domain
hello can anyone help me with unity iam trying to make multiplayer game using photon
and i have a problem in lobby part of the game, the rooms
#archived-networking has pins to photon server
you can turn off domain reloading but you can't cancel
and if its been long enough you probably are stuck
Yeah I just terminated unity in task manager and did all the lost progress again
;.-
okk le me see
do you have an inifite loop in your code maybe? if it happened when you pressed play
Your temp scene will exist if you ran it once. Dont reopen unity before looking for it in your folders
And your code is saved regardless so you dont lose everything for sure
Nah it just happened when maybe alt tabbing quite fast two times between my IDEA and unity while changing a very small thing. At least I think I dont remember rn
Oh that will save me so much time in the future 🙏 thx
do colliders check for scale changes every frame or are they listening to some kind of event?
I'm having trouble assigning a TMPro Text to a prefab. Is there something I'm missing? It's a very basic text I want to replace, but the script is on a prefab which get spawned in later
you cant reference scene objects from prefab unless said prefab is placed in that scene already
So I'd have to use something like GetComponent<> to be able to reference it?
Hey does anyone know how ot slow an animation relative to another animation with playableDirector
I have an animation that spins an object and one that opens and closes it
I want to slow down the spin animation
im tryna make a player shop
Guys, I have a WEBGL application and my users are having trouble making a request in the game and are receiving this message "Unknown Error - COD 500" and this problem is only happening with some users, in all our mobile test devices we do not have this problem, can anyone help?
GetComponent is wonderful, and you should use it a lot, primarily in setup (like Awake/Start/Enable/etc).
It isn’t quite as amazing if you try to spam it like in a collision callback, where you make thousands of calls per frame. But for setup, it’s really useful.
The first thing to do is check your server logs
it's not giving an error on the server :/
then you need to find out which URL is generating the error
you've given very little information
I know which url is the problem, when it is executed directly in the user's browser it works, but when it is called from within the unity it is giving this error
and it's not all handsets as we didn't have this problem with the test ones
if it is a HTTP 500 error, which I dont even know yet, there will be a log of it on your server if it was your URL that generated it
more likely to be browser specific rather than handset specific
Has anyone here done OAuth 2.0 in Unity with Azure? I have a .NET Core backend. How do I retrieve the token from the redirect URI to microsoft?
how would I go about checking if a animator has a specific blendtree with scripting?
whats the usecase exactly ?
I’m creating a blend tree from script to add weapon animations to my player that can be toggled from a randomized int… I can do all of that, but I need to check if the tree already exists to prevent it from making more than one.
This is for a weapon system where the animations are stored on the weapons themselfs to try and move away from having hundreds of animator transitions and allow for easy scaling with weapon additions. The idea is that each weapon can “instantiate” their own blend trees when equipped with their different anim sets which can be handled by methods within the weapon classes themselves
ohh this is beyond my skillset, I don't know much about animator lol didn't even know you can make blend tree from script 😛
soz
Animator overrides can do this
It's basically C# class inheritance, but for animators
Make one "base animator" with your blend tree, and many overrides where you change the animation clips
Gotcha, would you be able to shoot me a link to the scripting api?
https://docs.unity3d.com/Manual/AnimatorOverrideController.html
No scripting, all Inspector. The script is the usual one that tweaks the animator parameters
Well you can inject the animator override into the Animator Controller component to dynamically change the animations, even at runtime
I’ll give it a look, thank you!
What would be the best way to interact with a UI slider using a custom cursor? I have an implementation that accesses the OnDragBegin and OnDrag functions from the slider but it just sets the scrollbar to the maximum value and it cant be dragged back.
Forgive me, for I have sinned:
how to pass a refernece?
I'm programming and passing a material to the other gameObject and then deleting the original game object
but this is causing a crash because its trying to reference the original gameObject when setting the material
I'm trying to shoot something to make it a color then change it back after like 3 secons
aren’t materials reference types already? you should be able to assign it just fine?
the default behaviour should be giving a reference to the same thing
crashes
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.
did you instance your material during runtime?
the material is just in a folder
that is bizarre
private void OnCollisionEnter(Collision collision)
{
if (oMat != mat)
{
oMat = collision.gameObject.GetComponent<Renderer>().material;
collision.gameObject.GetComponent<Renderer>().material = mat;
collision.gameObject.AddComponent<ColorChange>();
collision.gameObject.GetComponent<ColorChange>().StartCoroutine(RemoveColor(oMat));
}
}
IEnumerator RemoveColor(Material originalMat)
{
yield return new WaitForSeconds(3f);
gameObject.GetComponent<Renderer>().material = originalMat;
}
}
yeah
not sure what I'm doing wrong
Is there anything wrong with my code logic wise
Give us the line the error is on.
I can't tell much from this.
gameObject.GetComponent<Renderer>().material = originalMat;
thats where it crashes
again, throws an exception. a crash would kill your entire game
and what is the full exception?
screenshot the console
please screenshot the console.
I find it interesting to see that the error references ColourChange, but your script tries to add ColorChange
let me fix that
still giving the same error
okay weird
even when I change it to material = null it still throws an error
Are you sure that is the line causing the error? It's talking about ColourChange, and that line doesn't have anything to do with ColourChange
the console tells me its that line
the console could be wrong though
but it stops crashing when I remove the line
Debug.Log(GetComponent<Renderer>().material.name);
this crashes it too
it really doesn't want me to access the material at all.
Not crashing, right? Just throwing an error? Or is the whole program closing down?
You should share the whole script using a paste site
!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.
using System.Collections.Generic;
using UnityEngine;
public class ColorChange: MonoBehaviour
{
public Material mat;
private Material oMat;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
if (oMat != mat)
{
oMat = collision.gameObject.GetComponent<Renderer>().material;
collision.gameObject.GetComponent<Renderer>().material = mat;
collision.gameObject.AddComponent<ColorChange>();
collision.gameObject.GetComponent<ColorChange>().StartCoroutine(RemoveColor(oMat));
}
}
IEnumerator RemoveColor(Material originalMat)
{
yield return new WaitForSeconds(3f);
Debug.Log(GetComponent<Renderer>().material.name);
}
}```
It changes the color but if I do GetComponent<Renderer>().material it throws an error.
there's a difference between GetComponent<Renderer>() and collision.gameObject.GetComponent<Renderer>()
think about it
but the removecolor is being run on the object with the color changed
you're getting the renderer for two different objects entirely
isnt that good?
doesn't matter at all which object you call StartCoroutine from
you called RemoveColor here
RemoveColor can only do one thing
get your OWN renderer
and print its name
it is on the colorchange script
public void RemoveColor() {
StartCoroutine(DoRemoveColor());
}
private IEnumerator DoRemoveColor() {
// the existing code
}
then from here you do :
collision.gameObject.GetComponent<ColorChange>().RemoveColor();
in fact...
oMat = collision.gameObject.GetComponent<Renderer>().material;
collision.gameObject.GetComponent<Renderer>().material = mat;
collision.gameObject.AddComponent<ColorChange>();
collision.gameObject.GetComponent<ColorChange>().StartCoroutine(RemoveColor(oMat));```
this whole damn process
should just live in a function on a script on the object you collided with
oh I see you're doing AddComponent?
You're doing a ton of useless/extraneous GetComponent calls here
collision.gameObject.AddComponent<ColorChange>();
collision.gameObject.GetComponent<ColorChange>().StartCoroutine(RemoveColor(oMat));```
Should be rewritten as:
```cs
ColorChange cc = collision.gameObject.AddComponent<ColorChange>();
cc.RemoveColor(oMat);```
(with these changes [#archived-code-general message](/guild/489222168727519232/channel/763495187787677697/))
so much simpler and more performant
works, thank you
so i've got an issue where my raycasts aren't working properly in build but are in the editor, has anyone encountered this?
I may have ran into issues like that before. Have you managed to try debugging it during the build, with any method it may be?
not yet, i just did a basic build after rebuilding my entire projectile system from the ground up to use raycasts because unity doesn't do proper collision checking for triggers at high speed to verify that nothing weird happened
and the raycasts seem to work maybe 5% or less of the time
Can probably log it via json or something, otherwise if you want to write yourself a console ^^
but yeah you'll probably want to check if it's being blocked for some arbitrary reason I'd say
Ah, there's this too
Unfortunately issues like that are kinda hard to debug via logs
how does friction work?
like, object1 has friction1, object2 has friction2. Is the friction between them the product of their frictions?
just checked the debug.log in the log after rebuilding it as a development build and the raycasts are passing right through the target more than 80% of the time
only at build not in editor
There are different friction combine modes on the materials
So my previous problem with rb/raycasting was using a webGL build, and in general there's a lot of stuff that likes to break between the dev and editor builds for that platform
i got really excited, and then realized that is a 3D only feature T.T
I'd suggest maybe trying to extend the ray a bit, and see if the problem is just the same regardless, otherwise could be some layering problems.
and maybe trying other methods than a raycast like a spherecast perhaps
the keywords you gave me helped tho, praetor. It helped me find a thread. 2D friction is a geometric mean
There is usually some optimization for physics on dev builds, so the precision being off still doesn't surprise me.
the ray is 100 units long, it's called on fixedupdate to make sure physics objects are properly placed, but it's still working maybe 50% of the time in the best tests and less than 1% of the time in the worst
and i have the character positioned between 3 and 10 units from the target in the test to make sure it's not spread calculations
Yeah, strange. Something to dig through the forums on. I'd try another casting method first off since probably more accuracy in those when you've larger colliders to check upon.
what other casting method would be viable for projectile hit calculations other than a raycast?
Can try an overlap sphere at the tip of it
and run that in update
not that exact performative method, but sometimes you have to give up that optimization for trickier things like percision
well what's odd is i had a problem where almost the exact same issue with the same success rate happened when i first changed to raycast, but it was fixed by turning the "update mode" to "animate physics" in the enemy animators
that doesn't really have the accuracy i need for a shooter game
There's a few things you can kinda do too, like grab the contact point and do some distance calculations
I just can't believe what an absolute headache raycasting in unity has been since i switched, you would think such a simple thing would be consistent but raycasting has been the most unreliable broken system i've worked with in a LONG time in anything
what are you raycasting at?
static colliders? rigidbodies? colliders on things being moved by an Animator?
Should give this a try. Toss as many extra calculations you need if you need that type of accuracy of a bullet.
just because you detect a collider, you can still continue to the next frame to decide when to discard the bullet.
I am raycasting at capsule colliders and box colliders with rigidbodies attached to the bones of ane enemy that is animated by an animator using root motion and animate physics
However in the testing I mentioned above the enemy is set to completely still and has no animation playing
I created a test scene that places the raycaster and the recipient at specific distances and run 200 tests with 198 hits in the editor and results varying from 30 to 120 hits in the build version
Unity's raycasting system has been a collosal waste of time and has set back my project 2 full work days because it's so inconsistent :/
whats a way to get the prefab parent of a child or grandchild's scripts
After you instantiate it, or as the asset instance?
After you instantiate it you can recursively use transform.parent and work your way up the tree until you find the component you're looking for using GetComponent()
What is the rigidbody sleep setting?
And wait, are the rigidbodies and colliders ONLY on the bones?
I would compare the results to a non-animated target.
You want to narrow down what's causing the problem.
How are you debugging? Make sure you visualize your rays too.
Some code and setup explanation(screenshots?) Would be helpful.
Draw the rays, pause on when the ray "goes through the object" and investigate the scene. Does the ray have the trajectory that you imagined? Is the desired collider in the way? Does it have any weird settings or suspicious stats in the rb?
Literally all we've been seeing from you is half baked complaints and barely any useful info on the setup and debugging.
The problem is only in build now, it works against a static object with 100% accuracy so the ray is both projecting from the right location and at the right angle, the layer mask is set up to ignore the parent objects of the skeleton so the rigidbody of the controller object shouldn't matter, I wrote code to visualize start and endpoint of Ray with sphere objects at low opacity and the start and endpoints pass directly through the enemy's hit box a large percentage of the time
Does anyone happen to know if you can upload partial updates to a Texture2DArray without sending the entire texture array back to GPU? E.g. updating and sending one slice only.
Because of the publisher and company guidelines it would be a violation of NDA for me to share large portions of production code or to show images/video of anything that resembles a development build, so posting a lot of that information is treading on thin ice
I tried experimenting with a line renderer since it only happens in a build and not the editor. But the linerenderer can't use the actual Ray itself so it's returning expected results every time and isn't being particularly helpful its more just drawing a line where the ray SHOULD be, not garaunteeing that it's drawing where the ray IS
anyone got any clue why my mouse1 input isnt going through
try capitalizing your 'update' method name to Update
You can use DrawRay instead of line. That's the closest you can get to a raycast.
The only thing that could change between a build and editor that is relevant to your issue is frame rate. Which might imply that something in the setup is dependent on it.
Well since it only occurs at build now not in the editor that's not an option
first time making a new texture2d at runtime, any first guesses on why it's seemingly transparent? can confirm referenceColor is set correctly, wondering if i need to convert it or something rather
Texture2D newTexture = new Texture2D(128, 128, TextureFormat.RGBA32, false);
Color[] cols = newTexture.GetPixels(newTexture.mipmapCount - 1);
for (int i = 0; i < cols.Length; ++i)
cols[i] = tile.materialPreset.referenceColor;
newTexture.SetPixels(cols, newTexture.mipmapCount - 1);
newTexture.Apply();
tileTextureMatrix[tile.tilePosition.x, tile.tilePosition.z] = newTexture;
does "set correctly" include a non-zero alpha?
Hi!
I've ran into a problem with Plastic SCM. One of the scenes (.unity file) has incorrect encoding now.
Its been a couple of months since I last edited the file and back then when viewing diff in Plastic I could properly see the YAML. Since then there was 1 other check-in of this file in a separate branch, which was later merged into the dev branch.
Now when I make a change in the scene, save and look at the diff - I see a bunch of gibberish. I have seen bug reports for Plastic about the encoding getting messed up with automatic merge, but these are from 2015, so I am a bit lost here... Has anyone encountered this type of issue?
Are you sure unity serializes the scene asset as text? Try opening the local file with a text editor.
I am pretty sure it is... Here are my reasons:
- In project settings under Editor -> Asset Serialization "Mode" is set to "Force Text"
- If I open any other scene in a text editor - it opens without a problem and I can read the yaml
- In Plastic if I right-click any scene file (both the one that I have a problem with and others that work fine) under "Change revision type" the "Text" option is inactive and the "Binary" option is active, meaning that right now the revision type is set to text.
Okay.
If it's really an issue with the encoding, it's probably because someone committed it with the wrong encoding. I don't think plastic itself changes the encoding of the assets.🤔
if you use #if Unity_Editor
in a class thats not in editor assembly how can you access editor scripts in the editor assembly ?
i need to access some static functions in the editor assembly from a scriptable object's code thats in the unity editor region
You can't. Editor assembly can't be referenced from the player assembly.
damn
The #if has nothing to do with it
well now i dont know how to link the two together
If the ScriptableObject is intended for editor only, then you could put it in the editor assembly.
nah its for game play but the data generated for it is editor only
mesh assets mostly
You can reverse the dependency. Make your editor script do something to the play data, not the other way around.
yeh i was about to ask why can i reference things in unity engine from editor but not the other way around
is that unity's design choice
Because there's no problem with including the play time code in the editor. In fact you need it to be able to test in the editor. However, in play mode you can't access any of the editor API. You'd need to include the whole editor binaries in every app.
ah i see - that makes sense
ill have to make a custom editor which calls the static functions then pass that to a public function in the target which is in a unity editor region i guess
seems custom editors will have to be acting as the middle man between the two
Is it okay to use Scriptable Objects to store Player Data such as health and progression?
sure, just note that changes to scriptable objects do not persist between game sessions except for in the editor
So it just goes back to the first values after a session?
yes. if you mean to save persistent data then you should serialize it and save it to a file in Application.persistentDataPath
I do want to save persistent data but I plan to save it in Unity Cloud Save instead.
but i think using a regular class would be better instead of a Scriptable Object in this case
I have this pretty basic character controller function running in fixedupdate but when i move and/rotate the parent of this charactercontroller my code doesn't take into consideration the new change, any tips on what i would need to do?
void Movement()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
velocity.y = gravity;
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
velocity.y += gravity * Time.deltaTime;
characterController.Move(velocity * Time.deltaTime);
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
characterController.Move(direction * speed * Time.deltaTime);
}
}
does gravity work?
it pushes me down but i don't think im ever grounded, would that be the problem?
are you sure direction and speed are ever != 0?
also new Vector3(horizontal, 0f, vertical).normalized should be Vector3.ClampMagnitude(new Vector3(horizontal, 0f, vertical), 1f)
oo ty
im code savvy but when it comes to this kinda player movement math im completely in the dark tbh
that whole code is quite situational/hacky, i'll expect you plan to make that a bit more robust eventually
you should, for example, only call Move once with the final delta you want to apply, not incrementally, thats just confusing.
Somewhat, design wise the movement is pretty close to where i'd expect it by the end of the project
I just have this issue where i rotate the parent (of the level and the player) but the charactercontroller move isn't playing well with the change
you probably want to redefine how horizontal/vertical input translates to world-velocity based on camera-position relative to the level/character orientation
I see
I figured it would have just worked since it's getting that rotation change aswell as a child
what you'd typically do as a first step is to project input, character.z and camera.z into the ground plane and make it relative to either the camera- or character-forward
Why does the camera need to be involved?
that depends on your setup
it doesn't have to be
if its not the camera, then its some other source that defines what local forward is
movement is typically relative to the character.z or camera.z
at least thats what a player typically expects/understands
if you rotate the world instead of the camera, you still rotate the camera/character relationship in the perception of the player.
anyway, just saying, you want to make input local to whatever your character orientation is
rotation stuff like that i can live with. its the un-synced movement that is the big deal
well, you are smoothing the movement
I assumed that was only relevant to actively influenced movements?
right now i rotate the parent and the player slides abit rather than moving with it in sync like how you would expect parent child behaviour
and you are using world space axes during the rotation which dont align with your grid axes
you can make the character a child of the world-chunk its currently walking on
whatever you do, you have to somehow make the player move in the local space of the world-chunk, that doesn't have to happen via parenting, you can also manually apply the chunk's transform matrix to the character
obviously it isn't doing it correctly
in any case, it looks like smoothing is to blame
nah still happens with the smoothing disabled
does it end up in the right place?
no
then your math is wrong
i would not be suprised
additional context
yellow player, green level. im rotating the planet back and forth, not pressing any of the input keys
Sorry for the late response, character controller yes
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
velocity.y = gravity;
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = Vector3.ClampMagnitude(new Vector3(horizontal, 0f, vertical), 1);
velocity.y += gravity * Time.deltaTime;
characterController.Move(velocity * Time.deltaTime);
//if (Input.GetButtonDown("Jump") && isGrounded)
//velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
characterController.Move(direction * speed * Time.deltaTime);
}
Is it possible to save a JSON file in unity cloud save without have to creating a file in the local system?
i don't have experience with unity's cloud save, but presumably you can give it a string? so just skip the step where you are creating a file and just give the cloud save the json string
alright thanks i'll try it out
Why does UIElements.Image exist when you can use UIElements.VisualElement? Is it just a wrapper? Also why not include it with the UIToolkit builder?
IIRC, VisualElement is the equivalent to an empty object, even though it can be decorated. Image is the concrete image class.
https://docs.unity3d.com/ScriptReference/UIElements.Image-image.html <= That is quite the disappointing documentation. @modest ledge I think you raise a good point.
Yeah I came across it earlier today and I was like, huh interesting. It doesn't exist in the builder but yet you can use it. So far I generally used a VisualElement with a background image to achieve the same result
What's the best way to associate asset keyed pairs? I was going to make a footstep system that reads clips from Dictionary<PhysicsMaterial, AudioClip> but it seems that during runtime dictionary contains PhysicsMaterial_1 and colliders with this material set read as PhysicsMaterial_1 (instance) which aren't equal and thus dictionary can't be accessed with later
I could do .Keys.Any with ID, name or some other shared property but is it the only way or I'm missing something?
You could maybe do Dictionary<int, AudioClip> and use the result of Object.GetInstanceID from the PhysicMaterial as the key.
Yeah when you access it, you get a new material reference
Yeah I'm doing it right now, just read it up on old forum post
InstanceID will be same across all runtime instances correct?
I suspect your referencing an asset at runtime and thus getting a whole new UnityEngine.Object factoried when you do.
Yeah, a little confused by the instances still
There's sharedmaterial as well but I forget what ref is used for that.
Ehhh... on second thought don't do that. It's guaranteed to be a unique number on instantiation.
Do you specifically want this to be a reference to an asset?
Right
It's for basic ux so I can drop asset and audio clip in editor, for serialization purposes it's a List<SurfaceFootstepPair> that gets converted to Dictionary<something, AudioClip> on begin play
Where "something" is some shared property that will alow me to compare against runtime instances of a physics material
A wild idea would be to use a name and chop of "instance" at the end 🤪
AssetDatabase.AssetPathToGUID() might help in that case.
Let me try
AssetDatabase is a UnityEditor class though?
I was under the impression it shouldn't be used in any things runtime
Checks Yeah, it is.
Ugh, there's probably something similar in Resources then.
Hmm, maybe not.
How are you getting access to project assets during runtime exactly? Unity games are supposed to be agnostic to the project file structure outside of special directories like Editor, Resources, Plugins, etc.
Cant you just dictionary a SO with material and sound clip
Sincerely hope this isn't true in latest versions
Yeah, but I'll still have to compare a physics material instance with physics material reference
Which to Unity are completelly different objects apparently
Why the material specifically? Compare by other types
It was the simplest design, I get benefit of physical properties and checking for footstep sounds at the same time 🤷♂️
I'm really just trying to port my Unreal system into unity right now
But if it's absolutely not possible I guess I could check against a tag or a layer or something
I would prefer to keep it physical material based tho
ScriptableObjects really aren't a bad idea. You don't need to use the PhysicMaterial as a key and could always get references via Linq if necessary.
Is there a way to convert game object to entity without subscenes
You mean to make some sort of a container component on my surface gameobjects that will hold a SO or something?
Didn't really get that
Depending on where exactly you are doing this, you can use GetEntity() which exists all over the API to take a GameObject reference and factory an Entity in the same way.
Entity entity = GetEntity(gameObject, TransformUsageFlags.Dynamic); should be the whole trick, I think.
I wanted to do the baking process without subscenes
In older version there was a component called ConvertToEntity something like that
Yeah, that whole pathway is gone (and good riddance, honestly).
I think you'll need to use IBaker . I'm not an expert on this (yet), but I think the baker class is required, else there is no instruction as to how to assign component data from a gameobject and monobehaviours.
I have the baker class in place I waned to start the baking process in a Scene Rather that Sub Scenes
Oh, so the entities live in the scene heirarchy?
Nope
Okay, that was a trick question lol.
I'm pretty sure that IBaker.GetEntity is public, so you don't need to using inside the baker class.
It works fine in subscene but not in the normal scene
Truly, I am a genius
So, if you have your baker set up and exposed where you need it (so like not a private class inside an authoring monobehaviour), you should be able to call it anywhere, like MyPreparedBaker.GetEntity(gameObject). There's no easy way to attach a script and convert otherwise, but I think any baker class should build basic entity components for things like LocalTransform, etc. for you if you don't need any special authored data.
I hate it.
Works as intended 😉
As long as it meets the requirements and not a lot of people will see it everything is fine
See, I really wanted to pass around classes that extend MonoBehaviours, but with type arguments somewhere in their ancestry. To do this and be able to store references in places where generics can't follow, I just cast everything to tuples of type (UnityEngine.Object, enum) to store, then cast back to retrieve.
{
public static bool IsNull(this (UnityEngine.Object, TouchControlGenericTypes) tuple)
{
if (tuple.Item1 == null || tuple.Item2 == TouchControlGenericTypes.Null)
return true;
return false;
}
}``` 😄
Actually, it felt like I cheated. 😄 It's not even reflection!
Blind casting in C# is pretty quick.
I have a situation right now where I destroy objects
how do you guys handle a situation where you destroy objects, OnDisable gets triggered to remove listeners from other components, but would throw a null reference because the publisher you're removing the listener to has already been destroyed
do I just check if the component is null or is there a better way to handle this?
just check it, and review the design (publisher was destroyed before subscriblers.....)
Does it make any sense to use assembly definitions for DLLs?
I have a few DLLs installed via the "NuGet for Unity" package. I noticed them while checking if any big chunks of third-party code were in the default assembly.
They aren't source files, so it's not like the compiler has to parse and compile a bunch of scripts.
e.g.
assem defs are for creating dll's so using them for existing dll's make no sense
yeah, I'm actually not sure how Unity would even interpret that
I guess I'm conflating projects with the DLLs that eventually get emitted
it's just a coincidence that each assembly definition creates a .csproj
my color assignment from script for a spriterenderer isn't actually causing the color to update
An assembly definition defines an assembly, and a dll is an assembly 😄
So no, but that was already answered
makes sense
it's odd, bcause when I click on the object, the spriterenderer color line is white, but when I click on the line, it says the color is there
but it isn't in render
is it transparent?
doesn't seem like it; there's no black bar at the bottom of the color field
The left of the two boxes in the top right of the color picker is the color it had when you opened the picker. Perhaps you have two scripts fighting over the color?
hmmm maybe
would making a new spriterenderer do that?
I shouldn't be making a new one every frame but maybe I am
hold on it might want it from 0-1 range but I was passing it in as 0-255
yup, that was it
random.seed gives me a random string of numbers right (ik its depracated I just need a random string of numbers rq)
nvm I can just use application.identifier
seed is used to seed the RNG
if you need a random string of digits, generate a random int
or repeatedly generate a single random number and append the result to a string
yeah that'll do
I'll have the player input a name or have like
a unique sending code
later
Guys I have a class and I want to store it in an array such that I can choose the extended class type in the editor in a drop down like this image (for different behaviours lets say). Is this possible or am I approaching it wrong?
you can do this only with:
[SerializeReference] and a custom editor script
oh okay thanks. Is there a better way to approach this? All i want to do is be able to select different behaviours of each element in the array in the editor?
the low tech way is to just use an enum and a switch case in your code
You can use an enum that will change the behaviour of the script
that's not a state machine
No?
just a modal switch
Okay thank you man 🙏
I'm pretty sure it is a state machine
You have logic when changing states
Then it behaves differently between each states
How is this not a state machine
a state machine is a mathematical model that defines states and transitions between them, an enum is just an enum, you can use an enum as a key to select states though
most people confuse a enum-driven switch statement for a state machine
Ah, yeah, I was thinking of enums as key to select states
without transitions you don't have a state machine
I see, thanks for clarifying
I'm concerned with writing clean code and the extendability of this system. If I envision it getting quite large I guess an enum implementation would create quite a large/messy script? If so would you guys suggest going the route of the [SerializeReference] method you mentioned? Just trying to find a good balance of time vs complexity i guess
this will not scale whatever you do
hmm yes i thought so, just to be clear by 'this' you mean enum?
Just use naughty's stuff
primarily because it exposes programming language features/details into UI and assumes your user is familiar with that inheritance structure and what it means, you should abstract the goal you want to achieve and make it independent of the implementation
no, your inspector design
thanks
Unity really needs to implement their own show/hide if alreayd
ah i see good point
even with a OOP design, it's hard to develop it perfectly
most of those niceties come with a performance overhead that is not nice to have in all cases
guys, how to resolve this errors?
Unity should just buy Odin
I hear interfaces also create some overhead, but I don't understand how you'd avoid using them in c#
also better serializeinterface support when
Large ? yes
Messy? No unless you do something silly. Basically the switch can be very simple using delegates:
public delegate void AbilityFunction(SomeParam x, SomeOtherParam y);
AbilityFunction f;
switch (abiilityType) {
case Fire:
f = SomeOtherClassA.FireFunction;
case Ice:
f = SomeOtherClassB.IceFunction;
...
}```
what I want is to have lets say an list of effects in the editor for an ability which I can add to/fine-tune, like lets say and explosion or a projectile, hence I want the UI to change based on what the effect is only exposing relevent fields for each effect. I think by doing it like this, the user doesnt need to have knowledge of what the effects do or how they work, they can just string them together. Like the particle system I suppose?
thanks man
All composition approach
which is why HideIf/ShowIf is more of a neccessity when assigning it via the editor
is that what its called? is this like a standard design pattern?
"composition" is a very broad concept
I wouldn't really call it a specific design pattern
Take a look at the shuriken particle system and that'll give you an idea how this system you want is to be developed.
thank you man will do
really appreciate you guys 🙏 so useful to be able to get quick answers from these channels
Hey all, do any of you guys know why Tasks might end up running faster than a bursted, parallel job?
I've set up an experiment where I increment a million integers every time Update() runs. I've got a version that uses a burst compiled job and another that uses concurrent C# Tasks. For some reason, the one using Tasks runs 2x faster than the job I've created?
What's more confusing is that this is all running in Mono, which I've heard brings down the performance of Tasks a ton. Can share code if it helps
is the task just await async void (not multithread) or task.run(create new thread)?
ah..you cant await "async void"
I've just had this idea and wanted to ask here if it seems feasible or would lead to constant headaches before testing it, but could you use scriptable objects to assign input actions from the new input system? Say attach an input action from the action map in which you could then have a function to edit bindings, etc...,
What might the limitations of this be and would it just end up being more work than it's worth?
https://github.com/mackysoft/Unity-SerializeReferenceExtensions does what you are looking for
depends on the details of your test, its very unlikely that a basic threadpool task runs faster than jobs since that API is NOT made for doing "work" its purely for representing async behaviour
that said, you can set up your tasks manually and do clever things (remove the training wheels that the job system forces you to use) and a c# thread can yield considerably more performance than Jobs, but NOT out of the box
you can also use SIMD and all the other math niftyness without burst, you just have to do it manually
I have a whole bunch of tasks stored in an array that I initialise using Task.Run, which I then feed into Task.WaitAll
I'm pretty much using all of macky's utility libraries and extensions. Good choice too beyond just hiding data. If we want complete optimization, I'd agree this would be the way, but when it comes to stuff you'd object pool, I wouldn't worry too much about caching some extra data.
At the end of the day, even if you make this really sweet system, you still have to fight with Unity's GUI to implement it all.
Ah, that’s really interesting - didn’t know that native C# threads could out-perform Jobs. Really unfortunate that this isn’t more widely known
It's possible your job is not configured properly to actually run in parallel
i think if you didnt need lock then async can run faster, acquire lock is an expenive operation
but if you use all unsafe container then there should be no lock in job system?
it's also possible your benchmarking is not accurate
or you are doing some expensive copying operations to marshall data between managed/unmanaged
the details are important
at the end of the day whether the code that actually runs is originally written in C++ or C# does not matter, the same machine instructions get executed. you just get a lot more automatic extra stuff and protection when you use various frameworks. You can strip down C# so much these days it practically runs like C++. But that is not doable with safe C#. Jobs gives you usafe C# that is still safe to use if you use the Jobs framework. But you can remove that framework too and live fully unsafe, and this opens all doors to implementing clever algorithms and cache optimization you can't access with Jobs.
Hi Folks. I'm reading JSON in from a service that I don't control. Within the JSON structure are sub-objects which describe different items using different attributes. How do I bring a JSON payload like this into Unity and C# when I can't really define the class upfront? If I was working in Ruby (which I know a lot better than C#) I'd use a hash, or in Python, a dictonary. Is there anything similar in C#?
why can't you make a DTO?
what is a DTO?
Data Transfer Object
ok, cool, thats something to read up on.
basically this.
when I can't really define the class upfront?
how come?
and yes c# does have dictionaries too ofc. but not sure what you would do it with instead
the JSON is a list a of games that have already been played (like in an arcade). there are some common attributes about each game, such as the name, platform and last time it was played. But there are also a bunch of attributes that are contextual to that game and don't appear in other games, such as one game has an attribute "max_level" while another racing game has a bunch of attributes for top_speed, best_lap_time etc. I can't build a class (or perhaps I don't know how to build a class) to store the total spectrum of attributes that could be used in the JSON.
Newtonsoft json.NET gives a pretty convenient JObject API for JSON without defining a DTO:
https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm
now that looks interesting! thanks!
it's pretty nifty
i have a scene that has a cube tagged mirror and that reflects the laserbeam
the laserbeam script defines what the laser beam is and it doesnt have a mono behaviour
the shootlaser script tells an object that your the laser pointer to shoot the laser here the code for the shootlaser one :
{
public Material material;
LaserBeam beam;
// Update is called once per frame
void Update()
{
Destroy(GameObject.Find("Laser Beam"));
beam = new LaserBeam(gameObject.transform.position, gameObject.transform.right, material);
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.right, out hit, Mathf.Infinity))
{
if (hit.collider.gameObject.CompareTag("Flower"))
{
Debug.Log("Laser beam hit a flower!"); // Print debug message when laser hits a flower tagged object
}
}
}
}```
as you see it uses raycasting and tags to find the collide of the beam with the flower
but when i play the game and collide the beam and flower , nothing shows up in the console.
any help on how to modify the code to work?
!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.
lateupdate calls after both update and fixedupdate right?
I wouldn't really say it runs "after" FixedUpdate
FixedUpdate is running at a separate cadence
It's true that FixedUpdate will not run between Update and LateUpdate, though.
any one?
give more detail on the setup , also start putting debug.logs to see whats happening instead
is this 2D or 3D, etc.
i did nothing happens
its 2d but the mirrors (cubes) are 3d so it reflects the laser better
screenshot the scene or something
the grey one is the flower tagged obj
whats the yellow line supposed to be
a laser beam
if (Physics.Raycast(transform.position, transform.right, out hit, Mathf.Infinity))
{
Debug.Log(hit.name)
i tried to detect the collision in another script but it just didnt work
i have that in my code
in the shootlaser script
its not tho
youre only debugging if it hits flower
put it outside and debug what ur hitting
well it does that
i mean it writes in the console
so what does it say
so is it printing Debug.Log(hit.collider.name)
what is the result of log
no i didnt write that i wrote some random words
in quotation marks
what good are random words?
Debug.Log("GRS");
how about debug something useful like I've stated
alright alright
that works too
then why doesnt it detect the object??
Tbh, half my debug statements are me slamming my keyboard.
Cube
UnityEngine.Debug:Log (object)
ShootLaser:Update () (at Assets/Scripts/ShootLaser.cs:22)
it detects the first cube
Goood! so your cube doesn't have the tag
it does
by first cube you meant the origin from?
so its hitting itself ?
the white cube here
1 solution : Move Ray origin outside of cube
2: solution : Use LayerMask and exclude white cube from Layers you look for
layers didnt work last time
i will try the first one
I bet they would if you did it correct lol
you have to use LayerMask , you probably used ints
nah i used layer mask
the first one works too you just need to make a new vector3 as Offset variable and do transform.position + offset
{
Destroy(GameObject.Find("Laser Beam"));
Vector3 rayOrigin = transform.position + transform.right * offset; // Adjust the offset value as needed
beam = new LaserBeam(rayOrigin, transform.right, material);
RaycastHit hit;
if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity))
{
Debug.Log(hit.collider.name);
if (hit.collider.gameObject.CompareTag("Flower"))
{
Debug.Log("Laser beam hit a flower!");
nextLevelButton.gameObject.SetActive(true);
}
}
}```
should i do it like this?
updated that and it still hits itself
Cube
UnityEngine.Debug:Log (object)
ShootLaser:Update () (at Assets/Scripts/ShootLaser.cs:24)
then you didn't add enough offset
how much you think is enough
aren't you adjusting it inside the inspector?
the offset variable
why not just use layermasks its dead simplelol..
private void OnDrawGizmos()
{
Gizmos.DrawSphere(rayOrigin, 0.24f);
}```
use this if you need to debug origin
i will try that too
alright
alr if you have trouble, show me what you tried
thanks for the help
the basic steps : Make new layer called "Player" or something
apply that layer to the main cube (important)
inside script add new
[SerializeField] private LayerMask mask;
Select in inspector only layers you want to hit in mask:
apply mask:
if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity, mask))
Anyone knows how to change a shadowcaster's shape via a script?
Im guessing i need to change this, but like, its read only
i've even tried to use that in my script
hmm cant you use Mesh as shape?
you said like this right ?
{
Destroy(GameObject.Find("Laser Beam"));
beam = new LaserBeam(transform.position, transform.right, material);
Vector3 rayOrigin = transform.position;
RaycastHit hit;
if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity, flowerLayer))
{
Debug.Log(hit.collider.name);
if (hit.collider.gameObject.layer == flowerLayer)
{
Debug.Log("Laser beam hit a flower!");
nextLevelButton.gameObject.SetActive(true);
}
}
}```
now the beam goes through the tagged object
and doesnt detect it
this wont work
hit.collider.gameObject.layer == flowerLayer
Mmm, how exactly?
i have that dont i?
also ify you're only looking for flowers then the layer check is useless
or you mean in another part of the code?
That's the point.
That code does not do what you think it does.
flowerLayer is a LayerMask, yes?
no i want to add other layers to it later
yes
a layer mask is a single integer
each layer is represented by a specific bit in that integer
so layers 0, 1, 2, and 3 are represented as 1, 2, 4, and 8
they're added together to produce the mask
a mesh is a series of verts, so probably just create that and pass it to the shape
the .layer property on a game object tells you the ID of its layer
0, 1, 2, 3, etc.
Even if it did give you a layer mask (1, 2, 4, 8, ...), that check would fail if your flowerLayer variable had more than one layer selected
if it had layers 2 and 3 selected, it'd have a value 12
4 + 8
To check if a layer is included in a layer mask, do this
bool matches = ((1 << layerNumber) & layerMask) != 0;
<< shifts bits over by a certain number of positions. Using a layer ID will give you these values.
Im thinking you can make a pologyon2D shape and then use that as your points for mesh ?
If you want to learn more about what the operator is doing, see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators
Yeah, but even if i do have a mesh shape, can i really asign it to the shadow caster shape?
cuz its read only
or am i misunderstanding how it all works
@uncut cape
also on that point from Fen
here a good graphic shows how it works in unity
https://unity.huh.how/bitmasks
ah, perfect
I should've checked that site for an example.
An integer has 32 bits, so that's 32 "yes" or "no" values. That's why layer masks work like they do.
yeah hold on, I'm getting mixed solutuons. I haven't done this myself because I dont really use 2D lighting.
hmm
let me check
well i added the things you said
but the beam still goes through the object
Show me your code.
alr
{
Destroy(GameObject.Find("Laser Beam"));
beam = new LaserBeam(transform.position, transform.right, material);
Vector3 rayOrigin = transform.position;
RaycastHit hit;
if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity))
{
Debug.Log(hit.collider.name);
bool matches = ((1 << hit.collider.gameObject.layer) & flowerLayer) != 0;
if (matches)
{
Debug.Log("Laser beam hit a flower!");
nextLevelButton.gameObject.SetActive(true);
}
}
}```
if its going thru it then ur other object doesnt have the layer ur looking for
omg
why
are u doing
this
bool matches = ((1 << hit.collider.gameObject.layer) & flowerLayer) != 0;
Seems fine. I showed it as an example for how to test if a layer is included in a mask.
Or did I flub something?
the physics raycast already have the layer variable they need though lol
this happends
they specifically don't want to hit their own layer (white cube)
as long as gray cube is inside another layerMask
put that inside raycast and it will only hit gray cubes
if gray cube is in layermask Flower
and raycasst only checks for Flower layer , then additionall if checks aren't needed , its only ever hitting Flower colliders
flowerLayer is a very bad name, btw
it should be flowerLayerMask if it's actually a layer mask
"layer" and "layer mask" are completely different ideas
so i should add a script for the gray cube so that if it collides with anything then do something?
if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity, flowerLayerMask))
{
Debug.Log("Hit object with flower layer");
{```
its this simple tbh
i don't see how this has anything to do with your problem
do this.
If you want to do specific things to specific things you hit, you should do that by checking for components on the object you hit
you don't want to make a layer for every single kind of thing you can shoot, after all..
well my problem is that the beam doesnt detect the flower
but what if the flower detect the beam?
did you put flower in the flowerlayermask
Fix your raycast. It will work perfectly well once you do it correctly.
Make sure that flowerLayerMask is a LayerMask that includes the layer the flower is on
That is a list of layers in your project
yes but did you apply it to the object
That does not answer navarone's question.
yep
Okay, so the target is on the correct layer, and has a non-trigger box collider.
ok so far looks ok, what about your current code
the shoot laser script?
Now show us flowerLayer in the inspector.
also this ^
I want to see that it includes the Flower layer.
wdym
.
I mean exactly what I wrote.
This is unrelated to my question. I asked you to show me where flowerLayer's value is set in the inspector
Or is that variable not set in the inspector?
This is why the name is bad. It sounds like I'm asking you about the flower layer
The name should be changed to flowerLayerMask -- or, even better, laserTargetMask
that's what the variable means
it's the things the laser can target
The script in the inspector
i dont understand "in the inspector"
do you know what the inspector is?
aslo ur missing the layermask here
Like this
ShootLaser has a flowerLayer field on it.
I want to see that field in the inspector.
Yes. Good.
Yeah, thats it
no i thought he means the code
make sure u fix this
U need to add the layermask here, as the last thingy
after math infinity
, LayerMask)
but with the name of ur layermask
whats problem with it
your missing layer mask bruh
this
no u didnt
And it still doesnt work?
not in the screenshot u showed
not in there
any ways
it still
doesnt work
lol
ok . did you save it after you changed
{
public Material material;
private LaserBeam beam;
public Button nextLevelButton;
public LayerMask flowerLayer;
// Update is called once per frame
void Update()
{
Destroy(GameObject.Find("Laser Beam"));
beam = new LaserBeam(transform.position, transform.right, material);
Vector3 rayOrigin = transform.position;
RaycastHit hit;
if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity, flowerLayer))
{
Debug.Log("Hit object with flower layer");
}
}
public void GoToNextScene()
{
SceneManager.LoadScene("NextScene");
}
}```
so its working
of course i did
do you not get the debug.log in console?
screenshot console in playmode
I shouldnt not work
show me how you draw the raycast
the beam script right?
yes
Also i still need help with this, maybe i should ask somewhere else too
😔
Cant find anything
maybe i havent been looking hard enough
📃 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.
im getting mixed answers on google :\
everything i saw was "workarounds" so im guessing there is no nice way to do it

what is
dir set to
public LaserBeam(Vector2 pos, Vector2 dir, Material material)
thats not a direction
where are u setting a direction at
anyway the visuals rn is not related to your main laser script. but I'm guessing youre not looking at the right direction
so is there any other problem with the script?
put this variables inside your class but outside the method
RaycastHit hit;
that affect the layers and all?
alr
lets draw some gizmos
private void OnDrawGizmos()
{
Gizmos.DrawSphere(hit.point, 0.23f);
Gizmos.DrawRay(transform.position, transform.right * Mathf.Infinity); ;
}```
put this inside your class
screenshot the game in playmode after (make sure to enable gizmos in Game vIew)
I have another plan for reference framing. Basically, I make a class to just log a given rigidbody’s local velocity (velocity it would have with no reference frame). Right before physics simulation, I convert all forces on an RB into velocity directly, using v += f m deltaT. Then I add/subtract reference frame velocity (and what ref frame velocity was after simulation) while keeping log of what the local velocity is supposed to be. Does this sound like a non-garbage idea?
my mind is probably not working but i get cs0103 for the transform and i have no idea how to fix that
huh ? this alone should not give you any errors..
did you move this RaycastHit hit;
from outside the method?
Maybe post the actual error instead of an error code value
nope
wait wtf
looks like this class is not a MonoBehaviour
ohhhhh
yeah thats the problem
i forgot that
in which case OnDrawGizmos won't work either anyway
he is right
this is the LaserBeam class probably?
Hit is unknown as well unless you've got some class instance variable..
no thats another code
why tho
to see it , but were still fixing the shootlaser..
yeah the OnDrawGizmos will need to go in the ShootLaser script
but you said the problem is with the laserbeam script
anyways
i will try that in the shoot laser script
no I said said the opposite
all good. just put ondrawgizmos in shootlaser script and lets see
btw what is it supposed to do
it doesnt do anything
lol
its supposed to show us where the ray is hitting and which direction
wouldn't hurt to put Debug.Log(hit.collider.name) in there too in the raycast
but visuals would help greatly
believe it or not
Look in the editor view, not in the game view
cant find it
double click your Game view tab
you will see it
its probably hidden
oh found it
can you disable your other script
what script?
LaserBeam
you mean i should delete the laser beam script and do the laser another way or im just stupid
right now the laser beam is conflicting showing the raycast debug..
i suppose to you can do Gizmos.color = Color.magenta; above the Gizmos
yeah ok
lol how do you use a class and not know how to reverse it
its a timezone problem
my mind is not working rn
at all
well its not hitting the cube thats for sure
the debug for hit is the middle of screen
which means its at 0,0,0
i can't see the ray line tho, put the color on both
ima guess its the white line?
this might just be a Z positio issue
are you sure both cubes are on the same Z position
yeah
checked that 100 times
no its not
Is the layer mask correct?
that the color of the beam
its white and yellow
they seemed to be from screenshots
yeah
i think
where do you. create lasorbeam visuals
you mean like the width , color , etc?
no thats not creating it
comment what out?
The two lines in the image
anything that invovlves beam and laserbeam
well then nothing happens
did u save? screenshot the scene
I'm assuming there's some misunderstanding occurring
lasterpointer is all the way on the left of the screen
yeah i think i didnt told you that
but i said there is a laser pointer
any ways
did you ? lol idk i think you got me lost somewhere
so now what
i was wondering why transorm.right was hitting something...
you said it was graycube but it was hitting white one
put the origin on the white cube?
but thats mirror
the mirror should reflect the beam
and the beam should reach the flower
ok so you want Vector3.reflect
btw the mirror is the white cube
well thats the whole point of the game
i meant white cube
oh yeah that another point of the game
anyway yea just get rid of the layermask in the raycast
Is there a way to "append" stuff inside a method, similar to having an overridable function called inside but having multiple scripts be able to add stuff? I essentially want delegates which alter a value.
Sorry if this is a dumb question as passing a value by reference into each delegate would work if it's possible
If anyone's curious, i found a solution
Maybe rephrase the question.
that works in my specific case
It's a little unclear what you're asking for
i just have an empty object parented to the umbrella, with the desired shadowcaster shape
and maybe tell us what you actually want to achieve in terms of gameplay or workflow
sometimes its the simplest solutions needed 😅
just sucks to manually do them all
it is, and i feel stupid that it took me so long to figure out!