#archived-code-general

1 messages · Page 208 of 1

night harness
#

unless im being silly

#

you probably don't want spread to be in actual units ig but the point still applies

latent latch
#

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

patent hound
#

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

cosmic rain
#

Why not just use playerCamera.forward+ someDisplacementVector?

#

Actually nvm.

#

You should rotate the camera forward by some random rotation

patent hound
#

it... apears to be working

#

this statement, that is Vector3 direction = (Quaternion.Euler(playerCamera.eulerAngles + spreadValue) * Vector3.forward).normalized;

cosmic rain
#

It would work. It's just not as intuitive for me as what I suggested.

patent hound
#

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

copper rose
#

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 >.<

latent latch
#

Anything is possible if you want to script it in

fervent furnace
#

two different programming languages

#

grammar

latent latch
#

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.

thick terrace
#

they used to be more similar but developed in pretty different directions over the years, they each have some features the other doesn't

night harness
#

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

latent latch
#

haha kinda looking like my voxel tool

night harness
#

😛 I'd imagine i'm walking on a very treaded on path. been fun so far

cosmic rain
#

A lot of things. They are similar sure, but it's like asking what's the difference between Spanish and Portuguese.

fervent furnace
#

i will just return the object since there is a unique value that indicates "failure"

#

the null

latent latch
night harness
#

bet. just wanted to vibe check it 👍

#

more or less same thing as trygetcomponent

fervent furnace
#
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

west lotus
#

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.

thin aurora
#

Or an id, but then you would need to know the id so a static identification might be better

west lotus
#

ah yes I can have a Dict of all Tasks on a manager

copper rose
latent latch
#

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.

royal temple
#

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!

copper rose
latent latch
#

Make a script and throw it on the same GO as the dropdown component

patent hound
#

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

scarlet viper
#

is gameobject.getcomponent faster than transform.getcomponent ?

cosmic rain
#

Though, the compiler would probably online it anyway.🤔

fervent furnace
#

i think the getcomponent finally calls go.getXXX?

quartz folio
#

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

night harness
#

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?

patent hound
night harness
#

world

jolly stratus
#

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

royal temple
#

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

patent hound
#

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

jolly stratus
#

@royal temple alrighty

patent hound
#

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

steep herald
#

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?

patent hound
#

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

leaden ice
patent hound
#

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

leaden ice
#

Which collider (s) in particular are you expecting to hit?

west lotus
patent hound
#

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

patent hound
#

always something simple

west lotus
dim crypt
#

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

pale ore
#

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?

graceful latch
#

unless you have a reason not to, use the built in update

pale ore
#

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

graceful latch
#

the entire point of classes is they are self contained for the most part

#

use built in updates

thick terrace
#

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)

graceful latch
#

for most cases you should just use Update()

thick terrace
graceful latch
pale ore
#

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

graceful latch
#

but could you not just call on collision enter when it hits?

#

and fixed update to move the bullet

thick terrace
graceful latch
pale ore
#

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

graceful latch
#

im confused what exactly does the shell handler do?

pale ore
#

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

trim schooner
latent latch
#

So basically like a coroutine manager for a single shot

pale ore
#

projectile and modifier are inheriting from part which is a scriptable object

#

only shell handler and player shooting are monobehaviors

latent latch
#

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

pale ore
#

is making coroutines for each shot expensive ,

#

?

latent latch
#

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.

pale ore
#

well it would just look like: for every ShellHandler in InstantiatedShells : ShellHandler.Update();

latent latch
#

even then, probably not that big of a problem for multiple different GOs to run the update

copper rose
hard viper
#

what are the physics implications of making a class that derives from Collider2D?

pale ore
latent latch
#

physics and colliders aren't inclusive to each other

hard viper
#

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

latent latch
#

Do you need to derive from it though

hard viper
#

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

latent latch
#

Perhaps some script that just takes in all colliders from the GO and work with that

hard viper
#

GO?

latent latch
#

gameobject

hard viper
#

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?

latent latch
#

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

hard viper
latent latch
#

Ah, makes sense. I should probably play around with it to get an idea how unity optimizes it all out of the editor.

lofty egret
#

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

rigid island
#

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.

little island
#

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

amber quest
#

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

rigid island
#

and if its been long enough you probably are stuck

little island
#

Yeah I just terminated unity in task manager and did all the lost progress again

#

;.-

amber quest
rigid island
lean sail
#

And your code is saved regardless so you dont lose everything for sure

little island
#

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

little island
orchid bane
#

do colliders check for scale changes every frame or are they listening to some kind of event?

regal epoch
#

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

rigid island
regal epoch
#

So I'd have to use something like GetComponent<> to be able to reference it?

hybrid turtle
#

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

safe dock
#

im tryna make a player shop

terse garnet
#

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?

hard viper
#

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.

knotty sun
terse garnet
knotty sun
#

then you need to find out which URL is generating the error

terse garnet
knotty sun
#

you've given very little information

terse garnet
#

and it's not all handsets as we didn't have this problem with the test ones

knotty sun
#

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

frank totem
#

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?

waxen burrow
#

how would I go about checking if a animator has a specific blendtree with scripting?

waxen burrow
# rigid island 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

rigid island
#

soz

simple egret
#

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

waxen burrow
simple egret
#

Well you can inject the animator override into the Animator Controller component to dynamically change the animations, even at runtime

waxen burrow
teal silo
#

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.

hard viper
#

Forgive me, for I have sinned:

fervent topaz
#

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

hard viper
#

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

fervent topaz
#

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.

hard viper
#

did you instance your material during runtime?

fervent topaz
#

the material is just in a folder

hard viper
#

that is bizarre

fervent topaz
#

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;
}

}

heady iris
#

a crash?

#

you mean an exception?

fervent topaz
#

yeah

#

not sure what I'm doing wrong

#

Is there anything wrong with my code logic wise

heady iris
#

I can't tell much from this.

fervent topaz
#

gameObject.GetComponent<Renderer>().material = originalMat;

#

thats where it crashes

heady iris
#

again, throws an exception. a crash would kill your entire game

fervent topaz
#

yeah

#

throws exception

heady iris
#

screenshot the console

fervent topaz
#

it wants to access ColourChange

#

which is the script's name

heady iris
#

please screenshot the console.

fervent topaz
#

Nothing else besies that

spring creek
# fervent topaz

I find it interesting to see that the error references ColourChange, but your script tries to add ColorChange

fervent topaz
#

let me fix that

#

still giving the same error

#

okay weird

#

even when I change it to material = null it still throws an error

spring creek
fervent topaz
#

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.

spring creek
#

Not crashing, right? Just throwing an error? Or is the whole program closing down?

fervent topaz
#

yeah

#

just throws error

#

sorry for my wording

spring creek
#

You should share the whole script using a paste site
!code

tawny elkBOT
#
Posting 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.

fervent topaz
#
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.

leaden ice
#

think about it

fervent topaz
#

but the removecolor is being run on the object with the color changed

leaden ice
#

you're getting the renderer for two different objects entirely

fervent topaz
#

isnt that good?

leaden ice
#

you called RemoveColor here

#

RemoveColor can only do one thing

#

get your OWN renderer

#

and print its name

fervent topaz
#

how do I do it then?

#

make it a function

#

?

leaden ice
#

The cleanest fix would be put that coroutine on the ColorChange script

#

and do this

fervent topaz
#

it is on the colorchange script

leaden ice
#
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

fervent topaz
#

works, thank you

patent hound
#

so i've got an issue where my raycasts aren't working properly in build but are in the editor, has anyone encountered this?

latent latch
#

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?

patent hound
#

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

latent latch
#

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

hard viper
#

how does friction work?

#

like, object1 has friction1, object2 has friction2. Is the friction between them the product of their frictions?

patent hound
#

only at build not in editor

leaden ice
latent latch
hard viper
latent latch
#

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

hard viper
#

the keywords you gave me helped tho, praetor. It helped me find a thread. 2D friction is a geometric mean

latent latch
#

There is usually some optimization for physics on dev builds, so the precision being off still doesn't surprise me.

patent hound
#

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

latent latch
#

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.

patent hound
#

what other casting method would be viable for projectile hit calculations other than a raycast?

latent latch
#

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

patent hound
#

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

latent latch
#

got that one too

#

thicker raycast haha

patent hound
#

that doesn't really have the accuracy i need for a shooter game

latent latch
#

There's a few things you can kinda do too, like grab the contact point and do some distance calculations

patent hound
#

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

heady iris
#

static colliders? rigidbodies? colliders on things being moved by an Animator?

latent latch
#

just because you detect a collider, you can still continue to the next frame to decide when to discard the bullet.

patent hound
#

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 :/

solemn wren
#

whats a way to get the prefab parent of a child or grandchild's scripts

latent latch
#

After you instantiate it, or as the asset instance?

patent hound
#

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()

spring creek
#

And wait, are the rigidbodies and colliders ONLY on the bones?

heady iris
#

I would compare the results to a non-animated target.

#

You want to narrow down what's causing the problem.

cosmic rain
#

Some code and setup explanation(screenshots?) Would be helpful.

cosmic rain
heady iris
#

yes.

#

yelling at the computer will not change its behavior.

patent hound
#

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

main cedar
#

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.

patent hound
#

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

onyx owl
#

anyone got any clue why my mouse1 input isnt going through

rocky basalt
cosmic rain
cosmic rain
patent hound
night harness
#

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;
heady iris
#

does "set correctly" include a non-zero alpha?

frozen oyster
#

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?

cosmic rain
frozen oyster
# cosmic rain Are you sure unity serializes the scene asset as text? Try opening the local fil...

I am pretty sure it is... Here are my reasons:

  1. In project settings under Editor -> Asset Serialization "Mode" is set to "Force Text"
  2. If I open any other scene in a text editor - it opens without a problem and I can read the yaml
  3. 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.
cosmic rain
#

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.🤔

broken light
#

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

cosmic rain
#

You can't. Editor assembly can't be referenced from the player assembly.

broken light
#

damn

west lotus
#

The #if has nothing to do with it

broken light
#

well now i dont know how to link the two together

cosmic rain
#

If the ScriptableObject is intended for editor only, then you could put it in the editor assembly.

broken light
#

nah its for game play but the data generated for it is editor only

#

mesh assets mostly

cosmic rain
#

You can reverse the dependency. Make your editor script do something to the play data, not the other way around.

broken light
#

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

cosmic rain
#

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.

broken light
#

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

hoary monolith
#

Is it okay to use Scriptable Objects to store Player Data such as health and progression?

somber nacelle
#

sure, just note that changes to scriptable objects do not persist between game sessions except for in the editor

hoary monolith
#

So it just goes back to the first values after a session?

somber nacelle
#

yes. if you mean to save persistent data then you should serialize it and save it to a file in Application.persistentDataPath

hoary monolith
#

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

night harness
#

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);
        }
    }
night harness
#

it pushes me down but i don't think im ever grounded, would that be the problem?

cold parrot
#

are you sure direction and speed are ever != 0?

night harness
#

speed is always 6 right now

#

im not sure on direction tbh

cold parrot
#

also new Vector3(horizontal, 0f, vertical).normalized should be Vector3.ClampMagnitude(new Vector3(horizontal, 0f, vertical), 1f)

night harness
#

oo ty

#

im code savvy but when it comes to this kinda player movement math im completely in the dark tbh

cold parrot
#

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.

night harness
#

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

cold parrot
night harness
#

I see

#

I figured it would have just worked since it's getting that rotation change aswell as a child

cold parrot
#

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

night harness
#

Why does the camera need to be involved?

cold parrot
#

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

night harness
cold parrot
#

well, you are smoothing the movement

night harness
#

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

cold parrot
#

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

night harness
#

that is already happening haha

#

that is why im confused

cold parrot
#

obviously it isn't doing it correctly

night harness
#

yes

#

the charactercontroller move code is ignoring it

cold parrot
#

in any case, it looks like smoothing is to blame

night harness
#

nah still happens with the smoothing disabled

cold parrot
#

does it end up in the right place?

night harness
#

no

cold parrot
#

then your math is wrong

night harness
#

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

cosmic rain
#

Does the sheep have a dynamic rb?

#

Character controller?

night harness
#
        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);
        }
hoary monolith
#

Is it possible to save a JSON file in unity cloud save without have to creating a file in the local system?

somber nacelle
#

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

hoary monolith
#

alright thanks i'll try it out

modest ledge
#

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?

earnest epoch
modest ledge
blazing tiger
#

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?

earnest epoch
latent latch
#

Yeah when you access it, you get a new material reference

blazing tiger
#

InstanceID will be same across all runtime instances correct?

earnest epoch
blazing tiger
latent latch
#

There's sharedmaterial as well but I forget what ref is used for that.

earnest epoch
#

Do you specifically want this to be a reference to an asset?

blazing tiger
#

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 🤪

earnest epoch
blazing tiger
#

AssetDatabase is a UnityEditor class though?

#

I was under the impression it shouldn't be used in any things runtime

earnest epoch
#

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.

latent latch
#

Cant you just dictionary a SO with material and sound clip

blazing tiger
#

Sincerely hope this isn't true in latest versions

blazing tiger
#

Which to Unity are completelly different objects apparently

latent latch
#

Why the material specifically? Compare by other types

blazing tiger
#

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

earnest epoch
tropic canyon
#

Is there a way to convert game object to entity without subscenes

blazing tiger
#

Didn't really get that

earnest epoch
#

Entity entity = GetEntity(gameObject, TransformUsageFlags.Dynamic); should be the whole trick, I think.

tropic canyon
#

In older version there was a component called ConvertToEntity something like that

earnest epoch
earnest epoch
tropic canyon
#

I have the baker class in place I waned to start the baking process in a Scene Rather that Sub Scenes

earnest epoch
tropic canyon
#

Nope

earnest epoch
#

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.

tropic canyon
#

It works fine in subscene but not in the normal scene

blazing tiger
#

Truly, I am a genius

earnest epoch
#

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.

earnest epoch
blazing tiger
earnest epoch
#

I hate it so bad.

#

I did something similar earlier today, actually...

blazing tiger
#

As long as it meets the requirements and not a lot of people will see it everything is fine

earnest epoch
#

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;
    }
}``` 😄
blazing tiger
#

If it works it works

#

If you're on a deadline if it works it works great

earnest epoch
#

Actually, it felt like I cheated. 😄 It's not even reflection!

#

Blind casting in C# is pretty quick.

blazing tiger
#

Programming is like the opposite of chess

#

You're encouraged to cheat

icy gate
#

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?

fervent furnace
#

just check it, and review the design (publisher was destroyed before subscriblers.....)

heady iris
#

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.

knotty sun
#

assem defs are for creating dll's so using them for existing dll's make no sense

heady iris
#

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

static matrix
#

my color assignment from script for a spriterenderer isn't actually causing the color to update

thin aurora
#

So no, but that was already answered

heady iris
#

makes sense

static matrix
#

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

heady iris
#

is it transparent?

#

doesn't seem like it; there's no black bar at the bottom of the color field

static matrix
#

yeah doesn't seem like it

#

also the object is there (it's that white square)

heady iris
#

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?

static matrix
#

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

heady iris
#

seed is used to seed the RNG

static matrix
#

I think

#

ah

#

so I will not use it for a random string of characters

heady iris
#

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

static matrix
#

yeah that'll do

#

I'll have the player input a name or have like
a unique sending code
later

gaunt blade
#

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?

leaden ice
gaunt blade
#

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?

leaden ice
celest iron
#

You can use an enum that will change the behaviour of the script

leaden ice
#

that's not a state machine

celest iron
#

No?

leaden ice
#

just a modal switch

celest iron
#

Huh, I thought it was

#

Anyways

gaunt blade
#

Okay thank you man 🙏

celest iron
#

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

cold parrot
#

most people confuse a enum-driven switch statement for a state machine

celest iron
#

Ah, yeah, I was thinking of enums as key to select states

cold parrot
#

without transitions you don't have a state machine

celest iron
#

I see, thanks for clarifying

gaunt blade
cold parrot
gaunt blade
#

hmm yes i thought so, just to be clear by 'this' you mean enum?

latent latch
#

Just use naughty's stuff

cold parrot
#

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

cold parrot
latent latch
#

Unity really needs to implement their own show/hide if alreayd

latent latch
#

even with a OOP design, it's hard to develop it perfectly

cold parrot
terse garnet
#

guys, how to resolve this errors?

celest iron
#

Unity should just buy Odin

terse garnet
#

I'm using external code

#

with [DllImport("__Internal")]

latent latch
#

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

leaden ice
gaunt blade
# cold parrot primarily because it exposes programming language features/details into UI and a...

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?

latent latch
#

All composition approach

#

which is why HideIf/ShowIf is more of a neccessity when assigning it via the editor

gaunt blade
heady iris
#

"composition" is a very broad concept

#

I wouldn't really call it a specific design pattern

latent latch
#

Take a look at the shuriken particle system and that'll give you an idea how this system you want is to be developed.

gaunt blade
#

really appreciate you guys 🙏 so useful to be able to get quick answers from these channels

formal wagon
#

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

fervent furnace
#

is the task just await async void (not multithread) or task.run(create new thread)?

#

ah..you cant await "async void"

reef garnet
#

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?

cold parrot
#

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

formal wagon
latent latch
#

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.

formal wagon
leaden ice
fervent furnace
#

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?

leaden ice
#

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

cold parrot
# formal wagon Ah, that’s really interesting - didn’t know that native C# threads could out-per...

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.

coarse narwhal
#

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#?

coarse narwhal
rigid island
#

Data Transfer Object

coarse narwhal
rigid island
#

and yes c# does have dictionaries too ofc. but not sure what you would do it with instead

coarse narwhal
#

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.

leaden ice
coarse narwhal
rigid island
heady iris
#

it's pretty nifty

uncut cape
#

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?
tawny elkBOT
static matrix
#

lateupdate calls after both update and fixedupdate right?

heady iris
#

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.

rigid island
#

is this 2D or 3D, etc.

uncut cape
rigid island
#

wdym its 2D but mirrors are 3D

#

you can't mix physics/colliders from 2D in 3D

rigid island
uncut cape
rigid island
uncut cape
rigid island
uncut cape
#

i tried to detect the collision in another script but it just didnt work

uncut cape
#

in the shootlaser script

rigid island
#

its not tho

#

youre only debugging if it hits flower

#

put it outside and debug what ur hitting

uncut cape
#

ohh ok

#

1sec

uncut cape
#

i mean it writes in the console

rigid island
#

so what does it say

uncut cape
#

the raycasting works fine

#

but it doesnt detect the object

#

thats the problem

rigid island
#

what is the result of log

uncut cape
#

in quotation marks

rigid island
#

what good are random words?

uncut cape
rigid island
#

how about debug something useful like I've stated

uncut cape
#

alright alright

uncut cape
#

then why doesnt it detect the object??

rigid island
#

still waiting

lime sonnet
#

Tbh, half my debug statements are me slamming my keyboard.

uncut cape
# rigid island

Cube
UnityEngine.Debug:Log (object)
ShootLaser:Update () (at Assets/Scripts/ShootLaser.cs:22)

#

it detects the first cube

rigid island
uncut cape
#

it does

rigid island
#

so its hitting itself ?

uncut cape
rigid island
#

right

#

so its hitting itself

#

you seee why we debug ?

uncut cape
#

yeah

#

so how to fix that

rigid island
#

1 solution : Move Ray origin outside of cube
2: solution : Use LayerMask and exclude white cube from Layers you look for

uncut cape
#

i will try the first one

rigid island
#

you have to use LayerMask , you probably used ints

uncut cape
rigid island
uncut cape
#
{
    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?

uncut cape
#

Cube
UnityEngine.Debug:Log (object)
ShootLaser:Update () (at Assets/Scripts/ShootLaser.cs:24)

rigid island
#

then you didn't add enough offset

uncut cape
rigid island
#

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

uncut cape
rigid island
#

as long as rayOrigin is not a local variable (put it outside a method)

#

debug it

uncut cape
#

alright

rigid island
uncut cape
rigid island
#

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))

marsh mesa
#

Anyone knows how to change a shadowcaster's shape via a script?

marsh mesa
#

Im guessing i need to change this, but like, its read only

#

i've even tried to use that in my script

rigid island
#

hmm cant you use Mesh as shape?

uncut cape
# rigid island alr if you have trouble, show me what you tried

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

rigid island
marsh mesa
uncut cape
rigid island
uncut cape
#

or you mean in another part of the code?

heady iris
#

That code does not do what you think it does.

#

flowerLayer is a LayerMask, yes?

uncut cape
uncut cape
heady iris
#

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

rigid island
heady iris
#

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;
heady iris
rigid island
heady iris
marsh mesa
#

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

rigid island
heady iris
#

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.

rigid island
uncut cape
#

but the beam still goes through the object

heady iris
#

Show me your code.

uncut cape
#

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);

      }
     }
    }```
rigid island
#

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;

heady iris
#

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?

rigid island
#

the physics raycast already have the layer variable they need though lol

uncut cape
#

this happends

rigid island
#

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

heady iris
#

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

uncut cape
rigid island
#
 if (Physics.Raycast(rayOrigin, transform.right, out hit, Mathf.Infinity, flowerLayerMask))
        {
            Debug.Log("Hit object with flower layer");

        {```
#

its this simple tbh

heady iris
heady iris
#

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..

uncut cape
#

but what if the flower detect the beam?

rigid island
#

did you put flower in the flowerlayermask

heady iris
#

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

heady iris
#

That is a list of layers in your project

rigid island
heady iris
#

That does not answer navarone's question.

uncut cape
heady iris
#

Show us the inspector for the flower object.

#

Capture the entire thing.

uncut cape
heady iris
#

Okay, so the target is on the correct layer, and has a non-trigger box collider.

rigid island
uncut cape
heady iris
#

Now show us flowerLayer in the inspector.

rigid island
#

also this ^

heady iris
#

I want to see that it includes the Flower layer.

uncut cape
uncut cape
heady iris
#

I mean exactly what I wrote.

rigid island
#

on the object

heady iris
# uncut cape .

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

marsh mesa
#

The script in the inspector

uncut cape
rigid island
marsh mesa
rigid island
marsh mesa
#

Like this

heady iris
#

I want to see that field in the inspector.

heady iris
#

Yes. Good.

marsh mesa
#

Yeah, thats it

rigid island
uncut cape
rigid island
marsh mesa
#

U need to add the layermask here, as the last thingy

#

after math infinity

#

, LayerMask)

#

but with the name of ur layermask

uncut cape
rigid island
#

your missing layer mask bruh

uncut cape
#

you mean i should add a layermask at the end?

#

yeah i did that

rigid island
marsh mesa
#

And it still doesnt work?

rigid island
#

not in the screenshot u showed

uncut cape
#

any ways

#

it still

#

doesnt work

#

lol

marsh mesa
#

Can u screenshot ur script again

#

the code

rigid island
uncut cape
# marsh mesa Can u screenshot ur script again
{
    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");
    }
}```
rigid island
#

so its working

uncut cape
rigid island
#

screenshot console in playmode

marsh mesa
#

I shouldnt not work

uncut cape
#

1sece

rigid island
uncut cape
rigid island
marsh mesa
#

😔

#

Cant find anything

#

maybe i havent been looking hard enough

uncut cape
#

its pretty long so i cant paste it here

rigid island
#

!code

tawny elkBOT
rigid island
marsh mesa
#

Did no one ever have to do that

#

i dont understnad lol

rigid island
marsh mesa
rigid island
uncut cape
rigid island
#

where are u setting a direction at

uncut cape
#

its just there

rigid island
#

anyway the visuals rn is not related to your main laser script. but I'm guessing youre not looking at the right direction

uncut cape
rigid island
uncut cape
#

that affect the layers and all?

rigid island
#

lets draw some gizmos

rigid island
# uncut cape alr
  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)

hard viper
#

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?

uncut cape
rigid island
#

did you move this RaycastHit hit;

#

from outside the method?

dusk apex
uncut cape
rigid island
#

wait wtf

leaden ice
uncut cape
#

yeah thats the problem

#

i forgot that

leaden ice
#

in which case OnDrawGizmos won't work either anyway

uncut cape
rigid island
#

😵‍💫

leaden ice
#

this is the LaserBeam class probably?

dusk apex
#

Hit is unknown as well unless you've got some class instance variable..

uncut cape
rigid island
uncut cape
#

give me the laserbeam script

rigid island
leaden ice
#

yeah the OnDrawGizmos will need to go in the ShootLaser script

uncut cape
#

anyways

#

i will try that in the shoot laser script

rigid island
#

no I said said the opposite

uncut cape
#

sorry

rigid island
#

all good. just put ondrawgizmos in shootlaser script and lets see

uncut cape
#

it doesnt do anything

#

lol

rigid island
#

make sure this is selected

rigid island
#

wouldn't hurt to put Debug.Log(hit.collider.name) in there too in the raycast

#

but visuals would help greatly

uncut cape
marsh mesa
uncut cape
#

cant find it

rigid island
#

you will see it

#

its probably hidden

uncut cape
#

oh found it

uncut cape
rigid island
uncut cape
rigid island
uncut cape
#

so it cant be attached

rigid island
#

so? just dont create the object

#

put a return statement before you do it

uncut cape
rigid island
#

i suppose to you can do Gizmos.color = Color.magenta; above the Gizmos

rigid island
#

lol how do you use a class and not know how to reverse it

uncut cape
#

at all

rigid island
#

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

uncut cape
#

checked that 100 times

uncut cape
dusk apex
#

Is the layer mask correct?

uncut cape
#

that the color of the beam
its white and yellow

rigid island
#

they seemed to be from screenshots

uncut cape
rigid island
uncut cape
rigid island
#

no thats not creating it

uncut cape
#

you mean how it is created?

#

its in the shoot laser script

rigid island
#

exactly what i mean

#

where do you call CastRay

uncut cape
rigid island
#

Ok comment those two out

#

then show scene again in playmode

uncut cape
dusk apex
#

The two lines in the image

uncut cape
#

the colors?

#

oh alr

rigid island
uncut cape
#

well then nothing happens

rigid island
#

did u save? screenshot the scene

uncut cape
dusk apex
#

I'm assuming there's some misunderstanding occurring

uncut cape
rigid island
#

yup just realized..

#

white cube and laserpointer are two different objects

rigid island
#

lasterpointer is all the way on the left of the screen

uncut cape
#

but i said there is a laser pointer

#

any ways

rigid island
#

did you ? lol idk i think you got me lost somewhere

uncut cape
#

so now what

rigid island
#

i was wondering why transorm.right was hitting something...

#

you said it was graycube but it was hitting white one

rigid island
uncut cape
#

the mirror should reflect the beam

#

and the beam should reach the flower

rigid island
#

ok so you want Vector3.reflect

uncut cape
#

btw the mirror is the white cube

rigid island
#

yea now I got that

#

shits confusing af

#

ngl

uncut cape
#

so i should add vector 3's?

rigid island
#

ok so

#

you DO need to hit the white cube

#

the whole layer thing is a bust

uncut cape
rigid island
uncut cape
rigid island
#

anyway yea just get rid of the layermask in the raycast

uncut cape
#

to reach the beam to the flower with the white cube

#

or the mirrors

rigid island
#

got it

#

Ill make a thread h.o

lyric atlas
#

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

marsh mesa
marsh mesa
#

that works in my specific case

leaden ice
marsh mesa
#

i just have an empty object parented to the umbrella, with the desired shadowcaster shape

cold parrot
marsh mesa
#

and i disable/enable each one of them when needed

#

the wide & the thin shadowcasters

rigid island
#

just sucks to manually do them all

marsh mesa