#archived-code-general

1 messages · Page 125 of 1

void quiver
#

can anyone point me in the direction of a good compute shader resource? I've been looking through some for the past week and just can't seem to grasp it. I'm trying to get a marching cubes implemented with them just for the sake of learning something new and it's been a brick wall.

#

and maybe I'm just trying to do too much

leaden ice
# void quiver can anyone point me in the direction of a good compute shader resource? I've bee...

This is the one that made it click for me
https://toqoz.fyi/thousands-of-meshes.html

#

it also involves some neat rendering stuff but there's a compute shader that does all the moving of the objects

void quiver
#

oh very cool, I'll check it out, thank you

nova moon
#

I have a question about subscenes. I'm really early in my project, an rts, and I decided to make the switch to DOTS before getting too far along and having to deal with it later. When reading the ECS workflow on Unity docs, it talks a bit about sub scenes, it seems like this is great for streaming scenes for performance vs loading a giant scene. So, my question is, if i'm just working in a test scene right now, and not building anything out with the environment or anything like that yet, I'm assuming I don't need to worry about sub scenes yet then?

high schooner
#

Not sure if anyone would like to take a try at my problem but any help is much appreciated. I have a script rotates the camera holder, head, to simulate recoil. When I attempt to shoot while the camera is rotated, the bullet hits where you were first aiming, even if the head was rotated up. I dont know if it is an issue with my projectile calculations (5th image attacked), but I find that unlikely as it is able to hit where you are initally aiming. If any more information is needed I would be more then happy to attach it

knotty sun
high schooner
heady iris
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.

heady iris
#

The least you can do is to post code in a way that is easy for other people to read.

knotty sun
worthy willow
#

Hey, I'm trying to call DestroyObj(); from multiple children objects from another script on this script. If I do GetComponentInChildren<> it works but only to one of the objects. I tried doing GetComponentsInChildren<> but I got an error. Any help?

mystic yoke
#

what is DestroyObj

knotty sun
mystic yoke
#

also that

#

you need to iterate the array and call DestroyObj on each item

worthy willow
worthy willow
mystic yoke
#

yes, that is the syntax for an array literal

heady iris
mystic yoke
#

GetComponents returns an array

heady iris
#

that's not useful

#

you got an error because you tried to call DestroyObj on a RecipeItem[]: an array of recipe items

heady iris
#

you can iterate over an array with foreach

#
foreach (var num in numberList) {
  Debug.Log(num + 1);
}
dawn nebula
#

I have a projectile whose rigidbody's collision detection is set to "continuous dynamic" moving through a trigger at high speeds. The trigger does not seem to react consistently. Any tips?

worthy willow
#

give me a minute

#

Awesome! it worked!

#

Thanks guys

mystic yoke
#

@worthy willow as a general tip, if something is acting differently than you would expect, the best first step is to read the documentation. Doing that would have told you that it returned an array, not an individual item

heady iris
#

(and to look at the error message)

mystic yoke
#

that too

worthy willow
#

Will do. thanks for the advice

mystic yoke
#

but it helps to read the documentation to better understand what the error message may be telling you

dawn nebula
#

Apparently continous collision just doesnt work with Triggers. Why?

lean sail
dawn nebula
lean sail
#

try Continuous Speculative then if u dont need very very precise collisions

#

which bullets are too fast to see anyways

dawn nebula
#

According to unity forums triggers just dont care about continous anything. Which I guess makes sense? If you hit something physical you're stopped, continous collision makes sense there, but if you're moving fast enough, you can obviously just... jump over the trigger completely in a single physics frame.
Then what do you do? Fire OnTriggerEnter and Exit at the same time? Does Stay go off?
It's definitely weird.

mystic yoke
#

you can raycast the velocity against triggers

#

as a workaround

void basalt
#

@dawn nebulaRaycast between your projectile updates for hit detection.

#

Not only is this much more performant than running actual physics bodies, but it's going to be much more accurate.

dawn nebula
#

ya it just changes who is doing the thing

#

as opposed to some arbirary trigger finding a thing and doing something, it's the projectile who does the search

#

and that's kinda annoying

void basalt
#

Everyone does projectiles this way. It's pretty much the standard.

#

You just can't rely on physics engines to perform hit detection on tiny bullets moving at 500 meters per second

#

It's never going to happen

dawn nebula
#

so should i do a raycast, getcomponent for some component I created and then call some method there?

latent latch
#

I've seen stuff where you'd also raycast behind if it's traveling too fast

#

rigidbody stuff does work though for high speed projectiles

void basalt
#

If the projectile is large enough, it could work

#

I still wouldn't rely on it

void basalt
#

where you bake the raycast behavior into it, and it returns a valid hit or not

#

If you remove rigidbodies from your projectiles completely, and move them manually using Transforms, you can get really nice performance

dawn nebula
#

I know that Unity has methods to raycast an entire collider shape as opposed to just a ray

void basalt
#

It depends on your projectile. Generally raycast is fine for little bullets

#

for a rocket, a shape cast would probably be better

dawn nebula
#

Hmm. Question then.

#

Right now I have a "gravity zone" that's a script with ontriggerenter/exit. Pretty massive collider usually so unless something is moving at ludicrous speeds I doubt it would miss it.

The point of this object is to tweak the velocity of any rigidbodies in its trigger by some value ever frame.

#

If it's the projectile itself that's handling the enter/exist of triggers, how do I cleanly replicate this behaviour?

void basalt
#

Yeah you'll probably want rigidbody projectiles for this then.

Whenever something enters the trigger, just check if it's a bullet. If it is a bullet, just disable the gravity for that bullet or whatever you're doing.

dawn nebula
#

I mean I'm doing that already. It's just I want these bullets to both interactwith potentially giant gravity zone triggers and also have sorta small hurtboxes to do damage to things it hits.

#

Guess I can just do both?

#

normal triggers for the gravity zones and raycasts for the hits

void basalt
#

If the gravity zone hitbox is really large, you don't really need to worry about it missing

#

the hit detection I'm talking about is for hitting thin walls, players, NPCs, etc

dawn nebula
#

so like

void basalt
#

you'll probably be fine

dawn nebula
#

probably fine

#

@void basalt For the calclation then should you project FORWARD into the next frame or check what you passed through last frame. i assume the former?

leaden solstice
#

If determinism is important then you might have to use... mathematics
You could make it multiple step, calculate with normal gravity until your bullet reach the trigger, and proceed rest with affected gravity

void basalt
#

is all you need to check

#

so yeah, you should check after they've moved

dawn nebula
#

after they've moved?

#

what if you teleport them?

void basalt
#

That would be moving

dawn nebula
#

ok but the hitbox would extend massively from your old position to the new one

void basalt
#

This tells you when the physics engine fires

void basalt
#

We aren't extending the hitbox of anything. We're just raycasting from lastPosition to currentPosition

#

It's just shooting a line between them, to figure out what it hit

dawn nebula
#

ya so if the projectile is somehow teleported between when you save the last position but before you do the raycast check from your current position, they raycast will extend from your current position to your pre-teleported location

void basalt
#

Don't think of this as a multi-threaded scenario. This usually won't happen

#

code gets executed from top to bottom, one line at a time, one file at a time

#

you should always be able to tell when your code gets executed

dawn nebula
#

no I get that

#

maybe I'm not explaining this correctly

void basalt
#

Code start -> Bullet move -> Player Move -> Bullet hit check

#

should generally be the order in which your code runs

#

as an example.

#

If your bullet moves, then teleports somewhere else, that new teleport position should be the current position.

#

you'll still have the same last position from the last simulation update

dawn nebula
#

this make sense or the ramblings of a mad man?

void basalt
#

reading

#

So when it teleports, you don't want it to check against the last position?

#

If so, just overwrite the last position when that happens.

dawn nebula
#

blegh

void basalt
#

then you'll have your lastPosition and currentPosition the same, and the hit detection basically will never return true after a teleport.

dawn nebula
#

why not check forward btw?

void basalt
#

because you'd be time traveling into the future

#

it would still work though

dawn nebula
#

i guess the difference would be, in the case where you destroy on the trigger overlap

#

for one frame the projectile would be in the trigger

#

but looking ahead you wouldn't ever see it in the trigger

#

assuming Update had a chance to fire

#

man

#

physics sims bruh

void basalt
#

You also only need to perform the raycast inside FixedUpdate

#

it would be wasteful to do it every Update() frame

#

(assuming you're still using rigidbodies)

dawn nebula
#

ye I figured

#

separate question

#

let's say I have 2 vectors

#

I want to rotate some third vector by the angle between those 2 vectors

#

how do

void basalt
#

@dawn nebulahttps://docs.unity3d.com/ScriptReference/Vector3.Cross.html

#

like this?

#

There's probably a better way of doing what you want

leaden ice
#

You're missing information in your question

dawn nebula
leaden ice
#

To get the angle

#

And make a quaternion with AngleAxis to rotate the vector by that angle

dawn nebula
#

Need an angle axis for signed angle

#

I guess that makes sense?

#

would that be the cross product of those 2 vectors?

#

@leaden ice

leaden ice
dawn nebula
#

what do I do with the quaternion?

#

multiply it by original vector?

leaden ice
#

multiply the black vector by it

#

to rotate it

dawn nebula
#

you mean the red?

leaden ice
#

no the black

lean sail
#

are u trying to rotate the black or red vector?

dawn nebula
#

red vector

leaden ice
#

psuedocode:

float angle = Vector3.SignedAngle(solidRed, dashedRed, axis);
Quaternion rotation = Quaternion.AngleAxis(angle, axis);
Vector3 result = rotation * originalBlackVector;```
leaden ice
dawn nebula
#

by the difference in angle between the two black vectors

lean sail
#

i thought it was the other way around from the drawing too

leaden ice
#

so that's what I wrote code to do

dawn nebula
#

aw shit mb then

leaden ice
#

yeah the drawing is the opposite - so my code above is going by the drawing

dawn nebula
#

I thought the doted vector and the "I need this" was enough to show I wanted the theoretical red

leaden ice
#

and then rotating the black by that 😆

#

either way

#

just do it the other way around

dawn nebula
#

alright clearly my paint skills are not up to par

leaden ice
#

same deal

wind palm
#

Pretty sure you can get the angle difference by doing

var diff = Quaternion.Inverse(fromRotation.rotation) * toRotation;

From and To may be reversed

dawn nebula
#

Thanks works.

leaden ice
#

oh yeah Quaternion.FromToRotation also works

urban stream
#

Hello! How do I make the variable "numberofJumps" add one when it's the ground instead of it waiting to add one after it gets off the ground? Here's my code: https://pastebin.com/Y9wUEkB1

#

Before you make fun of me, i will clean up the script im just trying to get things working

ionic adder
#

@urban stream Hot tip: clean up first before asking for help. You'll get help faster.

ember pine
#

that is pretty easy, just create a gameobject. Set the tranform ' forward and rotate it by 30 degress and now the new forward is result

hollow relic
#

i f*cked up

#

I used git on a unity project for the first time on something that is overdue

#

and now i have a merge conflict

swift falcon
#

Oh no

hollow relic
#

i truly done f*cked up

swift falcon
#

Idk how to help

#

Good bye

hollow relic
#

I FIXED?

#

dam

lean sail
#

merge conflicts are easy to fix, it just depends what the conflict was actually on

#

hopefully your fix doesnt mean u force pushed or something..

hollow relic
#

im on a different branch thankfully

wide ermine
#

idk if what im saying makes sense

#

and to check if it has changed you just do previouslyGrounded == isGrounded

gray mural
#

for example, I can jump no more than 3 times before I am grounded

#

you then need to make numberOfJumps variable, yes

#
private int currentJumps; // jumps in the air (when not grounded)
private readonly int maxJumps = 3; // let it be e.g. 3

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) && currentJumps < maxJumps) 
        Jump();
}

private void Jump()
{
    currentJumps += 1; // one more jump

    rigidbody.AddForce(Vector3.up, ForceMode.Impulse); // AddForce or whatsoever
}

private void OnCollisionEnter(Collision collision) // or smth similar
{
    if (collision.CompareTag("Ground"))
        currentJumps = 0; // when collided with ground - curentJumps is set to 0
}
#

@urban stream smth like this should work

gray mural
#

Does anyone know why are Backspace and Delete keys not triggered here?

private void LookForEvent()
{
    StartCoroutine(LookForEventCoroutine());

    IEnumerator LookForEventCoroutine()
    {
        yield return _waitForEvent;

        while (Event.PopEvent(_currentEvent))
        {
            print($"nice keyCode: {_currentEvent.type}");
        }

        StartCoroutine(LookForEventCoroutine());
    }
}
#

They should though. They are part of EventType.KeyDown, aren't they?

quartz folio
gray mural
#

TMP_InputField also has this thing

#

but it does work there

ashen shale
#

Does this work ? Meaning can I call a physics simulation in Update() ? Or shall I run it somewhere else ?

    void Update()
    {
         ...
        for (int i = 0; i < simulationSteps; i++)
        {
            ...
            SimulationScene.Simulate(Time.fixedDeltaTime);
        }
        ...
    }
void basalt
#

you're going to create massive lag

ashen shale
void basalt
#

which is why it will be so laggy

ashen shale
#

Ahaha, ok then I'll change my implementation

void basalt
ashen shale
void basalt
#

You can definitely do that with physics steps, and I know unity recommends it, however you will experience awful FPS drops

#

to the point where it just doesn't make sense

ashen shale
#

I know that I can use a math approach, thing is it is a space simulation. The game applies newton's law to the closest planet. So I figured that it is simplier to use physics steps

void basalt
#

Definitely best to avoid the physics engine in this case for predicting trajectories. Physx performance in scenarios like this is absolutely awful specifically when it simulates multiple times in a single frame.

#

Especially since it's already a space game with tons of stuff going on

ashen shale
#

What is your advice then ?

void basalt
#

You can obtain the velocity of rigidbodies

#

and you can estimate their path from that

finite hazel
wind palm
gentle rain
#

idk if this is the place to put this but I am currently working on a dream game that is similar to Tarkov, Rust, and DayZ but in VR and i need ideas because I suck at implementing things plus if I could get some help anyone who works with VR in Unity please DM me I would mainly ask for ideas but if I had a question or two like how shit stays and servers would work in VR again if this isnt the channel to ask please point me in the right direction

lean sail
ashen shale
#

since this is dynamic i figured that resimulate was the easiest thing to do

cold egret
#

- In my input service, i want to behave differently in build vs in editor. I read about the conditional compilation, but i'm not sure whether i use this properly or not, since rider tells me that some code is unreachable. So is this correct?

// meant to be "if in editor"
#if UNITY_EDITOR
    // get mouse input
    return Input.GetMouseButtonDown(0);
#endif
    // else return mobile device input
    return Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began;
fervent furnace
#

correct
since in editor the compiler will see both return statements and the return below is not reachable
but outside the editor the above return will not be compiled so the below one will be executed instead, if you want to get rid of the warning, you can use # else or #pragma warning disable (not recommended)

#

# if UNIXXXX
first return
# else
second return
# endif

cold egret
#

- And one more: i want to load a scriptable object from resources, get data from it and unload it immediately. Does Resources.UnloadAsset handle this? For some reason my data gets corrupted after calling it and this is very bad

muted root
#

pretty dumb question... why does my game build doesn't get recognized by discord for screensharing? is there anything i should do to fix this?🤔

dusk apex
#

Copying some data and not referencing it, hopefully.

cold egret
# dusk apex What're you doing with the SO?

- Here's how it's used. In a nutshell: load, read data, unload

var colors = Resources.Load<GameColorsConfig>(themePath);

var theme = new GameColorsRuntimeData();
theme.Load(colors);

Resources.UnloadAsset(colors);

- Behind the Load():

public void Load(GameColorsConfig data)
{
    PlayerColor = data.PlayerColor;
    ObstacleColor = data.ObstaclesColor;
    BackgroundColor = data.BackgroundColor;
    ParticlesColor = data.BackgroundParticlesColor;
}
dusk apex
#

Are they references or values (structs/primitives)?

cold egret
#

- Those are just color32

#

- I.e. values

dusk apex
#

What do you mean by your "data gets corrupted". I'm assuming, not the SO but the properties you copied.

cold egret
#

- No, SO values are changed

dusk apex
#

How are you verifying?

cold egret
#

- Alas, for me and my collegue it's different. For him, all colors are rest to (0, 0, 0, 0), and for me they get mixed

cold egret
dusk apex
#

Any subsequently loaded Scenes or assets that reference the asset on disk will cause a new instance of the object to be loaded from disk.

#

By docking, are you referring to loading them again? They wouldn't be the same assets.

cold egret
#

- By docking i mean selecting an asset, prossing alt+p and watching it from the editor. I.e. viewing it in unity through the inspector

dusk apex
#

What you see in the inspector wouldn't be what was loaded.

cold egret
#

- It's not about mismatch. Let's start from scratch, because this is going in the wrong direction

#

- The script above loads an SO asset from resources does not modify nor stores a reference to it, and unloads it. After this, for whatever reason, data inside the mentioned SO asset is changed

dusk apex
#

Create a new scene with only a simple script that simply loads and unloads the asset. Not modifying or copying any data. Ensure it isn't something else that you could be doing.

#

The data should not change.

cold egret
#

- Scriptable object has no setters on its properties. It simply cannot be modified with my scripts

#

- Furthermore, the above code is the only place where this asset and its class are used. Nowhere else in the game

#

- Here's the result of this btw. Before and after

dusk apex
#

I still believe you ought to isolate this problem by excluding anything and everything else that you've got in the scene.

#

Else this discussion will not go anywhere. Show that with nothing else in the scene, the data is corrupting.

cold egret
#

- While i'm setting it up, here's a quick note: after i remove the unload asset invokation, it does not corrupt assets anymore. Any thoughts on how can this be related?

dusk apex
#

Multiple access of the same asset on disc (inspector/programmatic etc) but I doubt it.

cold egret
# dusk apex Else this discussion will not go anywhere. Show that with nothing else in the sc...

- Same results. Here's the script that calls the above code:

public class SOCorruptionTester : MonoBehaviour
{
    [SerializeField] private GameThemes _gameTheme;
    [SerializeField] private bool _darkTheme = true;
    private ResourcesGameThemeResolver _themeResolver;

    private void Awake() =>
        _themeResolver = new ResourcesGameThemeResolver();

    private void OnValidate() =>
        _themeResolver?.Resolve(_gameTheme, _darkTheme);
}

- And also, this time the inspector crashed with an error. See screenshot. After i exited play mode, the error is gone and values are mixed again

#

- Console shows no errors btw

#

- I believe it's a bug on the unity's side?

#

- Hello?

dusk apex
#

I've created a test sample and could not generate your findings: ```cs
public class Sample : MonoBehaviour
{
public Color32 color;
private void Start()
{
var data = Resources.Load<SOExample>("Data");
color = data.color;
Resources.UnloadAsset(data);
}
}

public class SOExample : ScriptableObject
{
    public Color32 color;
}```But interestingly enough, if you access the the SO when resource attempts to load the data, you get an error.
#

Not inspecting the SO instance when the application runs, causes no issues.

#

The sample copies the correct color and the SO retains it's color.

cold egret
dusk apex
#

I'm not going to download or run your application.

#

I'll just show a tiny video of it being fine.

cold egret
#

- Bruh. Project, not application

cold egret
dusk apex
#

Not sure. I'm only informing you that I cannot reproduce what you've shown.

cold egret
#

- If you're worried about me hacking you or whatever lol, i can link a github repo of this project, where you can copy scripts yourself. But the folder hierarchy, scenes and SOs are up to you then

dusk apex
#

That's not my concern or my job. I'm showing you that it's not reproduced on my machine with the above code illustrated.

cold egret
#

- Again, cool, i'm glad it's not the case for you. But for me it is, any thoughts on that?

dusk apex
#

You've got something else going on.

cold egret
#

- And what could it be?

dusk apex
#

Reminder that viewing the SO instance while loading the resource causes the Unity Editor to crash.

cold egret
sharp root
#

Hi im trying to add Interstitial Admob ads every fourth scene change for my mobile game , however i get lots of errors , Heres the script

#

`using UnityEngine;
using GoogleMobileAds.Api;

public class InterstitialAdManager : MonoBehaviour
{
private InterstitialAd interstitialAd;
private int sceneChangeCount = 0;
private int interstitialFrequency = 4; // Number of scene changes before showing interstitial ad

private void Start()
{
    // Initialize interstitial ad
    string interstitialAdUnitId = "YOUR_INTERSTITIAL_AD_UNIT_ID";
    interstitialAd = new InterstitialAd(interstitialAdUnitId)
    {
        AdUnitId = interstitialAdUnitId
    };

    // Create an ad request
    AdRequest request = new AdRequest.Builder().Build();

    // Load the interstitial ad
    interstitialAd.LoadAd(request);

    // Subscribe to the OnAdClosed event
    interstitialAd.OnAdClosed += (sender, args) => HandleOnAdClosed();
}

// Method called on scene change
public void OnSceneChange()
{
    sceneChangeCount++;

    // Check the scene change count
    if (sceneChangeCount >= interstitialFrequency)
    {
        // Check if the interstitial ad is ready to be shown
        if (interstitialAd != null && interstitialAd.IsLoaded())
        {
            // Show the interstitial ad
            interstitialAd.Show();

            // Reset the scene change count
            sceneChangeCount = 0;
        }
    }
}

// Event handler for the interstitial ad closed event
private void HandleOnAdClosed()
{
    // Load a new interstitial ad when the previous one is closed
    AdRequest request = new AdRequest.Builder().Build();
    interstitialAd.LoadAd(request);
}

}
`

#

Any help would be appreciated

#

(I think im using outdated things in my script)

mellow sigil
#

You'll have to show the error messages too

sharp root
#

I will

#

'InterstitialAd' does not contain a constructor that takes 1 arguments

#

'InterstitialAd' does not contain a definition for 'AdUnitId'

#

'InterstitialAd' does not contain a definition for 'LoadAd' and no accessible extension method 'LoadAd' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)

#

'InterstitialAd' does not contain a definition for 'OnAdClosed' and no accessible extension method 'OnAdClosed' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)

#

'InterstitialAd' does not contain a definition for 'IsLoaded' and no accessible extension method 'IsLoaded' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)

#

'InterstitialAd' does not contain a definition for 'LoadAd' and no accessible extension method 'LoadAd' accepting a first argument of type 'InterstitialAd' could be found (are you missing a using directive or an assembly reference?)

#

Thats it

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.

gray mural
#

3 "`" at the beginning and end

mellow sigil
#

Let me guess, you got this code from ChatGPT?

sharp root
#

YEAH

mellow sigil
#

ChatGPT produces nonsense code. You'll have to start over, read the actual documentation. It has examples.

sharp root
#

I know it has i just cant figure it out

gray mural
mellow sigil
#

I've blocked you

gray mural
#

and how?

gray mural
#

ask ChatGPT not to write the whole code, but parts of it

gray mural
unborn bronze
#

Not sure where to ask this but how do I make a liquid

gray mural
marsh wadi
#

anyone who could tell me what this is?

heady iris
heady iris
#

you have two (or more) cameras in your scene

ashen shale
#

I have this code:

for (int i = 0; i < simulationSteps; i++)
{
    Gravity.calculateGravity(ghostPlanetsObj, ghostRocketObj, true);
    TrajectoryPhysicsScene.Simulate(Time.fixedDeltaTime);
    Debug.Log("ghostRocketObj.transform.position: " + ghostRocketObj.transform.position);
    lineRenderer.SetPosition(i, ghostRocketObj.transform.position);   
}

What I see is that ghostRocketObj.transform.position keeps the same coordonates
calculateGravity make some calculations and ends with AddForce for ghostRocketObj.

native prawn
#
    public void SeekForPlayer()
    {
        Vector3 rayOrigin = new Vector3(0.5f, 0.5f, 0f); // center of the screen
        float rayLength = 20f;
        Ray ray = turretCam.ViewportPointToRay(rayOrigin);
        Debug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, rayLength))
        {
            if (hit.collider.tag == "Player")
            {
                Debug.Log("Did Hit");
            }
        }
    }


So I need to check if the raycast hits something or not.
But whenever I touch the raycast nothing happens? And I have no idea what I did wrong

marsh wadi
dusk apex
native prawn
dusk apex
# native prawn yes

Either the raycast failed to hit anything or whatever it hit was not tagged as player.

quartz folio
#

Use CompareTag, not equality, to compare tags

dusk apex
quartz folio
#

it's fine as is, and is a world point

dusk apex
#

Ah, ui. Viewport.

quartz folio
#

It's a ray coming out of the center of the camera

heady iris
#

every camera gets rendered every frame

native prawn
#

It does work now, but the thing is that the raycast isn't going further than the red line. Even though the maxdistance is a lot

quartz folio
#

Surely it's just hitting the object your camera is in

native prawn
quartz folio
#

So, print what it's hitting then and find out

frail meteor
#

Hi there, I need help regarding converting an array of byte into an AudioClip.

I'm building a WebGL app that in runtimes should be able to receive MP3 audio from the website backend where its hosted.

Since its not possibleo to directly send MP3s from website to the app I have to follow this pipeline:
Site generates the mp3 -> converts it into an array of bytes -> converts it into a string -> send it to the app via the SendMessage method.

Now after receiving the string I need to do the opposite, I already did the string to []byte conversion but I'm stuck at creating the audioclip since it indeed create a clip but on play the audio its just a mix of noises. Is somebody able to help?

Here's the script I'm using: https://hatebin.com/drkzqdzrbn

(Before suggesting to use a WebRequest I can't point to a link since the audio is different each time and its generated at runtime)

native prawn
quartz folio
heady iris
#

i.e. a WAV file

native prawn
heady iris
#

it's a long list of loudness values

#

you would need to decode the MP3 data first

#

i suspect you'll need to grab a third party library for that

#

trying to interpret MP3 data as a WAV gives you some very weird sound.

frail meteor
latent fossil
heady iris
frail meteor
heady iris
#

to turn MP3 data into PCM data

#

which AudioClip.Create can ingest

frail meteor
#

ok

#

Can I look for generic libraries or should I search for unity specific one? Sorry I've never been in this situation

latent fossil
sleek bough
ashen shale
#

Can directly apply AddForce to an object which is in another scene ?

#

eg:

private GameObject ghostObj;
...
SceneManager.MoveGameObjectToScene(ghostObj, OtherScene);
...
Rigidbody2D body = ghostObj.GetComponent<Rigidbody2D>();
body.AddForce(forceVector);
vague jolt
#

I am getting thi error:
NullReferenceException: Object reference not set to an instance of an object
snapToGrid.snap () (at Assets/Script/snapToGrid.cs:42)
ObjectPlacer.Update () (at Assets/Script/ObjectPlacer.cs:95)

ON this line

if (objectPlacer.instantiatedStructure == gameObject)

this is inside a function called snap that is called every frame and I added the following if

        if(objectPlacer.instantiatedStructure != null)
        {
            snap();
        }

But didn't fix,
Is also called here in the object placer script in this way:

        if (instantiatedStructure != null)
        {
            instantiatedStructure. GetComponent<snapToGrid>().snap();
        }
vague jolt
swift falcon
#

hi.. would a trigger work if its parent game object has the rigid body componened (the child game object has the trigger and the script that has the on trigger methods)

vague jolt
vague jolt
#

np

ashen shale
vague jolt
#

thatr void is execture once when you open the scene

#

in that moment you read the player prefs and add a force

#

just remember that player prefs don't get deleted even if you uninstall the game, so you need to delete them or set them back to zero when you start the game

ashen shale
#

Aaah well I do set the scene in the onStart method and it is kept in global

#

but you're saying that not enought ?

swift falcon
#

well I added a game object that has a rigidbody component and it didnt work

vague jolt
#

the only way to save data between scenes is by actualy saving the data, there are many ways to do it player prefs is an easy one

#

wait

#

Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.

● Easy Save: https://bit.ly/2BzgdXb

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

·····················································...

▶ Play video
ashen shale
vague jolt
#

this should help

vague jolt
#

becase i am 99 percent sure that you can't have two scene running at the sae time

potent sleet
#

wrong

vague jolt
#

ah my bad

ashen shale
latent latch
#

Would a singleton work for that

#

assuming it's on a single scene

vague jolt
#

well you learn something new every day

potent sleet
#

thats why load Additive exists lol

latent latch
#

otherwise static data probably

ashen shale
#

My problem is that I have a GameOject in the TrajectoryScene and I don't know why AddForce doesn't work on it

latent latch
#

Oh, huh interesting

swift falcon
#

ok one question... is there a way to make overlapsphere last for seconds? and have it report all the object that were inside of it

latent latch
#

^cast it multiple times

dusk apex
#

Cast it every frame for x seconds

woven matrix
#

hey guys need some help, I am using this code to get me a signed angle on two points the target and the origin, but if the origin rotates the angle changes until the rotation stops

 Vector3 targetDirection = target - OriginTargetingAngle.position;
            
            float angle = Vector3.SignedAngle(initialForward, targetDirection,OriginTargetingAngle.right);
            float clampedAngle = Mathf.Clamp(angle, -90f, 90f);
vague jolt
#

A script

potent sleet
#

no shit

#

but its null

vague jolt
#

The line i sent

dusk apex
#

Object placer is null

vague jolt
#

If object placer .instantiated == gameobject

vague jolt
dusk apex
#

NRE occurs when you attempt to access a member of a null reference.

potent sleet
#

^

vague jolt
#

Thats strange because object placer is on a gameobjsct that is ne er deleted

swift falcon
frosty lynx
#

How would I convert a SceenSpaceReflectionPresetParameter to an int or atleast how do I modify it? I'm using Unity 2014 with BuiltIn.

dusk apex
#

The reference being null isn't an issue. The error would occur the moment you attempt to access a member.

latent latch
swift falcon
#

thank you

#

what i am trying to do is using triggers, i made a box rigidbody, and there's another object that's moving based on its parent's movement.. when the trigger is hitting the box rigidbody, it is not summoning on trigger enter... i dont know why

vague jolt
#

But in void start i defign objectPlacer = GameObject.Find("Controller").GetComponent<ObjectPlacer>();
}

dusk apex
frosty lynx
vague jolt
#

And that script never gets removed

dusk apex
frosty lynx
potent sleet
#

debug.log it

dusk apex
potent sleet
vague jolt
#

Now i can't try but i will check it more later. At least i know whatto check

#

Wait

#

Why the error is not calling on the if in the void update ?

#

But instead in the if in the void snap. Shouldn't it call before there?

potent sleet
dusk apex
#

You're unable to test print anything so you ought to ask this question later when you're able to debug properly.

vague jolt
#

Tanks any way

frosty lynx
north warren
#

the 2nd Log constantly shows y=1.0000

twin hull
#

@north warren don't set quaternion directly

potent sleet
#

seriously

#

should never have to do that ever

north warren
potent sleet
#

use Euler

north warren
#

First time deaaling with C#, first time using Quaternions

north warren
potent sleet
#

ye

#

there's built in functions

north warren
#

This ?

potent sleet
#

if thats Global Volume should be fairt simple

north warren
#

Yes never had to deal with Quaternions

#

First time using Unity, im cloning a project i was previously making using Panda3D

#

what's with the w component

#

Oh nvm

#

actually do mind

potent sleet
#

you dont new a quaternion method

north warren
#

Oh that's odd

#

quaternion specific ?

potent sleet
#

is a static function

north warren
#

Oh okay

#

im not calling a struct

#

but a function

potent sleet
#

the function is in the struct

#

freaky

north warren
#

Okay but honestly im still not getting the result im looking for

potent sleet
north warren
#

im making this car game and i want to make the camera follow the car

potent sleet
#

simple. use cinemahchine

#

forget this rotatioons crap

lusty dune
#

Child the camera

potent sleet
#

that will look like shit

#

don't do that

lusty dune
#

Hmm...

potent sleet
#

if you wanna a stiff barely able to adap camera sure

#

parent it

#

quick follow.. ok

#

i can see why it was bought

ashen shale
#

I manage to create the new scene, to move the goshtObjects to it

north warren
#

what is this cinemachine

ashen shale
#

I can compute physics but I can't apply it

ashen shale
north warren
#

alright so gotta head to pkg manager ?

#

and after that ?

lusty dune
#

Oh boy

north warren
#

yes but how do i set the follower itself ?

#

is it some component ? im still fairly new to unity

latent latch
north warren
#

Oh i found smth

polar bane
ashen shale
polar bane
#

I can't open any project...

polar bane
#

I've been trying all day

#

can't get it fixed

somber nacelle
polar bane
#

can't find them

somber nacelle
#

if only there were some sort of convenient button that would open up the crash logs. since neither of us can read i guess we can assume it doesn't exist

polar bane
#

I've been trying for so long

polar bane
fiery geyser
#

I'm creating a spline like this:

using UnityEngine;
using UnityEngine.Splines;

namespace MCBEAddoner.Nodes
{
    public class ConnectionCreator : MonoBehaviour
    {
        public Transform startMarker;
        public Transform endMarker;
        public Spline spline;

        private void Start()
        {
            spline = new Spline();
            
            Vector3 startPosition = startMarker.position;
            Vector3 endPosition = endMarker.position;
            
            float segX = Mathf.Abs(startPosition.x) + Mathf.Abs(endPosition.x) / 4;
            float segY = Mathf.Abs(startPosition.y) + Mathf.Abs(endPosition.y) / 4;

            if (startPosition.y < endPosition.y)
                segY = -segY;

            Vector3 startMiddlePoint = new Vector3(startPosition.x + segX, startPosition.y - segY);
            Vector3 endMiddlePoint = new Vector3(endPosition.x - segX, endPosition.y + segY);

            spline.Add(new BezierKnot(startPosition));
            spline.Add(new BezierKnot(startMiddlePoint));
            spline.Add(new BezierKnot(endMiddlePoint));
            spline.Add(new BezierKnot(endPosition));
            
            spline.Warmup();
        }
    }
}

but it doesn't render, why?

heady iris
#

because a spline is just some data

#

why do you expect it to render a mesh?

fiery geyser
#

idk, the Spline component did

#

how can i make it render a 2d line?

frail meteor
#

https://hatebin.com/uaifbmpagy

This is the code I use to receive an mp3 that was previously converted into an array of bytes and then into a string to be able to enter in a SendMessage()

It works like a charm on unity editor but doesnt work on WebGL, probably due to the limitation to not be able to use 'Application.persistentDataPath' and other local memory related things once hosted on website.

Can somebody help me out figuring out if its possible to convert it?

(posting on this channel cause it is a webgl issue but its mostly a code related thing)

knotty sun
frail meteor
#

So yeah basically I use UnityWebRequestMultimedia to generate the file from the array

#

I tried with AudioClip.Create but seems that it works for WAVs and not MP3s

heady iris
#

oh dang, there you go (:

frail meteor
#

am I wrong?

knotty sun
#

you are wrong. you just need to use a different protocol depending on your target platform

north warren
#

For the yaw damping in cinemachine, can you make its range bigger AND its movement slower

knotty sun
north warren
#

right now the more the yaw damping, the more the range AND the movement get bigger

frail meteor
north warren
knotty sun
#

mobile has it's own particular problems because of file security

frail meteor
frail meteor
#

It didn't worked :c

#

This is the suggestion coded, should be fine

heady iris
#

well, yeah, it 403'd

#

something is wrong with your request

frail meteor
#

"Please note that in WebGL, the use of local file paths such as "file://" + tempFile is only available when running the game from the local file system (file:// protocol). If you plan to deploy the WebGL build on a web server, you need to use UnityWebRequest.Get or UnityWebRequest.Post to fetch the audio data from a server endpoint rather than accessing local files directly."

Could this be? found on chatgpt
Also the request goes fine on editor...

#

I really can't understand what should be adjusted :/

coarse vine
#

hello, this is a bit unrelated but I and trying to develop in VS not using unity just a normal project and whenever I debug the console closes right after compiling the code can anyone help me?

potent sleet
#

i already redirected you to the C# discord

coarse vine
potent sleet
#

you didnt even wait 2 minutes

potent sleet
#

also Console applications close after runs

#

unless you put Console.ReadLine() at the end

coarse vine
potent sleet
#

or you hold the app inside a while loop

coarse vine
#

I know but is there a permeant solution?

potent sleet
#

that's how console application works

#

you can't change that

coarse vine
#

that was cringe idk why i put that

potent sleet
coarse vine
#

anyways thanks for your help

jovial salmon
#

Does Assembly-CSharp.dll not exist in the latest version of unity 2021?

#

I've reinstalled twice already and I can't get rid of this error on an old project even when moving the assets to a new one

potent sleet
#

delete library folder

#

try again

#

wait for rebuild

jovial salmon
frail meteor
#

@knotty sun sorry for the ping man, when you have time please check the reply. 🙏

fiery geyser
#

anyone here has a tutorial for a zoomable panel?

cold briar
#

I'm gonna need to use Netcode for Entities for a project of mine and so I'm trying it out on a local project, but the out-of-the-box project (2D URP+Entities, Entities Graphics and Netcode For Entities in 2022.3.1f1) already came with a memory leak warning which I ignored and started following a tutorial on Netcode For Entities hoping it would disappear. Not only it didn't disappear but there are now even more memory leaks.
The video I'm following is this one: https://www.youtube.com/watch?v=WlWDus1h5YE
I followed the video all the way to the end and I have the same as him, but if you don't want to watch it, this is the code I have rn:

  • NetcodeBootstrap.cs
using Unity.NetCode;
using UnityEngine.Scripting;

[Preserve]
public class NetcodeBootstrap : ClientServerBootstrap
{
    public override bool Initialize(string defaultWorldName)
    {
        AutoConnectPort = 2134;
        return base.Initialize(defaultWorldName);
    }
}
  • GoInGameSystem.cs
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;
using UnityEngine;

[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation | WorldSystemFilterFlags.ThinClientSimulation)]
public partial struct GoInGameClientSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.Temp)
            .WithAll<NetworkId>()
            .WithNone<NetworkStreamInGame>();
        state.RequireForUpdate(state.GetEntityQuery(builder));
    }

    [BurstCompile]
    public void OnDestroy(ref SystemState state)
    {

    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.Temp);
        foreach ((RefRO<NetworkId> id, Entity entity) in SystemAPI.Query<RefRO<NetworkId>>().WithEntityAccess().WithNone<NetworkStreamInGame>())
        {
            commandBuffer.AddComponent<NetworkStreamInGame>(entity);
            Entity req = commandBuffer.CreateEntity();
            commandBuffer.AddComponent<GoInGameRPC>(req);
            commandBuffer.AddComponent(req, new SendRpcCommandRequest { TargetConnection = entity });
        }
        commandBuffer.Playback(state.EntityManager);
    }
}

[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct GoInGameServerSystem : ISystem
{
    public ComponentLookup<NetworkId> NetworkId;

    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        EntityQueryBuilder builder = new EntityQueryBuilder(Allocator.Temp)
            .WithAll<GoInGameRPC>()
            .WithAll<ReceiveRpcCommandRequest>();
        state.RequireForUpdate(state.GetEntityQuery(builder));
        NetworkId = state.GetComponentLookup<NetworkId>(true);
    }

    [BurstCompile]
    public void OnDestroy(ref SystemState state)
    {

    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        FixedString128Bytes worldName = state.WorldUnmanaged.Name;
        EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.Temp);
        NetworkId.Update(ref state);

        foreach ((RefRO<ReceiveRpcCommandRequest> reqSrc, Entity recEntity) in SystemAPI.Query<RefRO<ReceiveRpcCommandRequest>>().WithAll<GoInGameRPC>().WithEntityAccess())
        {
            commandBuffer.AddComponent<NetworkStreamInGame>(reqSrc.ValueRO.SourceConnection);

            NetworkId networkId = NetworkId[reqSrc.ValueRO.SourceConnection];

            Debug.Log($"{worldName} connecting {networkId.Value}");
            commandBuffer.DestroyEntity(recEntity);
        }
        commandBuffer.Playback(state.EntityManager);
    }
}
fiery geyser
fiery geyser
#

no

#

just a normal panel in a canvas

cold briar
#

When using UI Toolkit, you have to specify that you want to update a certain element, I don't think the same applies to the default UI elements

fiery geyser
#

that i want to update a specific element?

cold briar
#

yeah

gray mural
fiery geyser
#

before

#

it doesn't resize what i instantiate

cold briar
jovial salmon
gray mural
#

probably in PlayerPrefs or json if you gonna e.g. move scenes or whatever

real comet
#

What's the best way to make a multiplayer physics based game sync properly? It's turn based to latency isn't much of a problem, but collisions look either goofy because of interpolation or choppy when I use network transform. I am using normal physics rn but its not deterministic so the server sync is really visible which I don't really want

#

Using Netcode for GameObjects

somber nacelle
latent latch
real comet
#

Ah, thanks for the redirection

soft shard
#

What might be a good way to handle logging with an object pool? (and by "good" I mean least I/O work without missing logs) Would it make sense to use a StreamWriter thats always open for the duration of the game and periodically writes a batch of logs, or on every single new entry or when the pool recycles the oldest entry? Should I make a new streamwriter and close any previous for every log? Or would there be a better approach in general? For context, im working on a logging system for a Windows build so I can see Debug.Log happen in game and when certain events trigger, so sometimes it could be writing logs every frame or sometimes just a few every so-often

vague jolt
#

I have many game object with a script inside, thats script is called snapToGrid, if i get the reference of one gameObject and get his component and do snapGrid.snap(); is the function snap called only for that gameobjct script ?

leaden ice
#

When you paint your house you are not painting every house in existence.
When you fill your car with gas, you are not filling every car in the world with gas

vague jolt
leaden ice
#

it is

vague jolt
#

arguable

leaden ice
#

When you understand it it is

#

Object oriented programming is just that

#

there's an object

#

you are calling a method on the object

#

not on the concept of a SnapToGrid

#

but that particular SnapToGrid

vague jolt
#

because i am getting this error
NullReferenceException: Object reference not set to an instance of an object
snapToGrid.snap () (at Assets/Script/snapToGrid.cs:43)
ObjectPlacer.Update () (at Assets/Script/ObjectPlacer.cs:97)

And i don't get why

leaden ice
vague jolt
#
        if (snapGrid != null)
        {
            snapGrid.snap();
        }
#

but i am checking if that thing is null

leaden ice
#

show your full script

vague jolt
#

can i send the github scripts

#

?

leaden ice
#

Or is this ObjectPlacer line 97

#

I think it's ObjectPlacer line 97

leaden ice
vague jolt
leaden ice
#

if (objectPlacer.instantiatedStructure == gameObject)

vague jolt
leaden ice
#

so objectPlacer is null

vague jolt
#

thats why i am confused

leaden ice
#

objectPlacer is null

#

not gameObject

vague jolt
#

but i never disable the script

leaden ice
#

so?

#

what does that have to do with anything?

vague jolt
#

how can it be null

leaden ice
#

it was either never assigned, or it was assigned to null

vague jolt
#
    void Start()
    {
        insideX = (x % 2) / 2f;
        insideY = (y % 2) / 2f;
        outsideX = -insideX;
        outsideY = -insideY;
        objectPlacer = GameObject.Find("Controller").GetComponent<ObjectPlacer>();
    }
#

here is clearly declared

leaden ice
#

that's not a declaration that's an assignment

#

And the right side of that can be null

#

GameObject.Find("Controller") could return null

#

and so can GetComponent<ObjectPlacer>()

vague jolt
#

yes but the script works, is just when the gameobject is instanted that it returns the error, than it works as intended

leaden ice
#

Either you don't have an active object in the scene named "Controller", or that object does not have the ObjectPlacer component on it

leaden ice
vague jolt
leaden ice
#

show the full stack trace of your error

#

it could also be you are calling the snap() function before Start runs

vague jolt
leaden ice
#

click on the error

#

to see the full stack trace at the bottom

vague jolt
#

NullReferenceException: Object reference not set to an instance of an object
snapToGrid.snap () (at Assets/Script/snapToGrid.cs:43)
ObjectPlacer.Update () (at Assets/Script/ObjectPlacer.cs:97)

leaden ice
#

so where is ObjectPlacer getting the snapToGrid reference from?

vague jolt
leaden ice
#

show the ObjectPlacer script

leaden ice
vague jolt
#

sorry i sent before the wrong script

leaden ice
#

this is definitely the proble,m

#

you're calling snap right after you instantiate it

#

that will be well before Start() runs

vague jolt
#

makes sence

leaden ice
#

Simple fix here is take this:

    void Start()
    {
        insideX = (x % 2) / 2f;
        insideY = (y % 2) / 2f;
        outsideX = -insideX;
        outsideY = -insideY;
        objectPlacer = GameObject.Find("Controller").GetComponent<ObjectPlacer>();
    }```
#

and just rename that to Awake()

vague jolt
#

whats the difference ?

leaden ice
#

Awake will have run already by the time Instantiate returns

#

it runs as the object is created

tropic quartz
#

Awake happens before start. Like... awake happens on all existing objects first, before start runs on anything afaik. And then Update.

vague jolt
#

yes problem fixed

#

thanks you really much

leaden ice
# vague jolt thanks you really much

To be honest I would probably also just remove this:

        //before placing the structure is important to make it snap so we are sure that is actually placed
        if (instantiatedStructure != null)
        {
            instantiatedStructure. GetComponent<snapToGrid>().snap();
        }```
and put this in snapToGrid:
```cs
void OnEnable() {
  snap();
}```
vague jolt
#

my code is horrible so i am using the actuall transform.position and it happened that the game object was not snaped before

#

so it would mess every thing up

#

so i just run snap before placing it

red sapphire
#

Hi there, I am currently trying to implement photon into my openxr project and I have the head linked up, however my hands are in the wrong position and rotation. The hands with the prefab and my xr hands are also rotationally and positionally aligned to each other. Here is my scrpt to set the positions:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;

public class NetworkPlayer : MonoBehaviour
{
[SerializeField] private Transform head;
[SerializeField] private Transform leftHand;
[SerializeField] private Transform rightHand;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    MapPosition(head, XRNode.Head);
    MapPosition(leftHand, XRNode.LeftHand);
    MapPosition(rightHand, XRNode.RightHand);
}

void MapPosition(Transform target, XRNode node)
{
    InputDevices.GetDeviceAtXRNode(node).TryGetFeatureValue(CommonUsages.devicePosition, out Vector3 position);
    InputDevices.GetDeviceAtXRNode(node).TryGetFeatureValue(CommonUsages.deviceRotation, out Quaternion rotation);

    target.position = position;
    target.rotation = rotation;
}

}`

leaden ice
red sapphire
#

Its just to do with the hand alignment

#

All of the positions in the unity editor are at 0,0, as shown by the second image

#

in the editor they are fine

leaden ice
#

huh?

#

is there a difference between "editor" and "unity editor"?

#

it's unclear which image is the "correct" thing and which is wrong

#

and what photon has to do with it

#

you should start by just looking at the hand GameObject in scnee view with tool handle rotation set to Local first

#

to make sure the object itself is oriented properly

#

perhaps your 3D model is imported incorrectly for example

red sapphire
#

it is the same 3d model, how do I set the gameobject to local?

leaden ice
#

set tool handle rotation to local by selecting it in the scene view overlays

#

or pressing X to toggle between local and global

#

assuming thats what you mean by "set the gameobject to local?"

red sapphire
# leaden ice it's unclear which image is the "correct" thing and which is wrong

btw to be more clear on the right hand image, the left hand is the xr hand and the right is the photon prefab hands, its just showing that the rotations are the same in both. the left image is showing how the rotation in the photon hand is dramatically different to the rotation in the xr hand, despite them having the same rotation before i press start game

red sapphire
shadow laurel
#

I am attempting to allow my game to register if there is a controller connected, or if there isn't to just use keyboard inputs. But the controller connects, disconnects, then reconnects, but no input from the controller is registered. If I unplug the controller it still registers as connected, but I can still control it from keyboard, unlike what I wish to do which is disable keyboard inputs in the game when a controller is plugged in.

I am using the unity manual code for detecting controllers as seen below
IEnumerator CheckForControllers() {
while (true)
{
var controllers = Input.GetJoystickNames();

            if (!connected && controllers.Length > 0) 
            {
                connected = true;
                Debug.Log("Connected");
        
            } else if (connected && controllers.Length == 0) 
            {         
                connected = false;
                Debug.Log("Disconnected");
            }

            yield return new WaitForSeconds(1f);
        }
    }

and this is my code for registering inputs

    private void OnEnable()
    {
        if (playerControls == null)
        {
            playerControls = new PlayerControls();

            if (connected == true)
            {
                playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
                playerControls.PlayerCamera.Movement.performed += i => cameraInput = i.ReadValue<Vector2>();
            }
            else if (connected == false)
            {
                playerControls.PlayerMovementKeyboard.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
                playerControls.PlayerCameraKeyboard.Movement.performed += i => cameraInput = i.ReadValue<Vector2>();
            }
        };

        playerControls.Enable();
    }

please help

heady iris
#

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

heady iris
#

i can just OR together some bitshifted stuff, but it's kinda gross

novel kayak
#

Help me please

potent sleet
heady iris
#

is that actually the correct line number? it looks fine

#

it would be a problem if you were doing MapZone.transform.SetParent

potent sleet
#

I think you're setting the prefab parent and not the actual instantiated MapZonep

somber nacelle
heady iris
#

Ah, that would do it.

smoky pike
#

https://paste.ofcode.org/sHyTXzdL6hPfwF2XFL2KY3
I have the following code where in the start screen(containing text), the user presses on the screen "tap to start" to begin the game. Once this happens, I want to instantiate all the objects with the tag of "Dot" with a 1 second interval. If the player presses the wrong dot, they die, and a tap to restart screen shows up, resetting the entire scene.

Problem: when the player dies, i want the tap to restart screen to stay there until the user taps on the screen again to restart. Right now, once the player dies, the scene gets reloaded immediately and the restart text doesn't show up

potent sleet
#

right now it's not doing anything

smoky pike
potent sleet
#

that coroutine is literally doing nothing

#

it waits 1 second once it runs but doesn't actually do anything after 1 sec

#

coroutines run async they wont pause the method you ran it from

#

unless it was a coroutine as well and using yield

#

you're just creating a new routine each dots iteration

#

but its empty

smoky pike
#

oh how would I fix that?

potent sleet
# smoky pike oh how would I fix that?

don't put it in a loop first of all so you 're not just creating a bunch

IEnumerator DotTimeGap()
    {
        yield return new WaitForSeconds(1.0f);
//Logic that needs to wait 1 second 
//SumMethod();
    }```
#

if you want a continuous running thing then use a while loop

novel kayak
#

@potent sleet I've tried to set the MapZonep = Instantiate(MapZone,position*2, Quaternion.identity,transform);

and now i get another error:

Cannot instantiate objects with a parent which is persistent. New object will be created without a parent.

And yes the error occur only on playmode.

@somber nacelle It has the same issue

Sorry for the late response but I've tried to find solutions.If i dont set any parent to the object I won't get errors , but the instantiation won't have any parent,and that's wrong in my case.

somber nacelle
#

yeah you are 100% calling the method on a prefab. you need to get a reference to the instance of the component that has the createleftMap method on it, then call the method on that instead of on a prefab

#

show the code where you are calling that method. please share the entire class in a bin 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.

balmy radish
#

I have a question about materials and shaders
Anyone has time for help?

somber nacelle
balmy radish
#

Wait in which Channel do i have to ask a question about Mats?

somber nacelle
balmy radish
#

oh thx ^^ n sry for dat

fading trail
#

should i make a voxel engine via using a 2D array noiseMap and then evaluating the height based on an AnimationCurve
OR
use an array that gets all dimensions of the map via noise and then store that
OR
should I use the first for the surface and the latter for the underground

smoky pike
potent sleet
smoky pike
#

So when the user presses on a "bad" dot, the restart text doesnt show up at all

lethal tusk
#

how can I search for a word in a json file?

fading trail
uneven gulch
#

yo im new to coding and game development and i might have a few dumb questions to ask if any1 could help lmao

potent sleet
lethal tusk
potent sleet
# smoky pike ah

can you show/describe the issue a bit beter im confused on what u asked

lethal tusk
#

i want to know if there is some data exist or not, if not make some default data

potent sleet
#

File.ReadAllText
iirc

#

or ReadAllLines

smoky pike
# potent sleet can you show/describe the issue a bit beter im confused on what u asked

so basically I "tap to start" the game, once I do, the dots instantiate with a one second delay, the user has to press on the "good" dots. If the user presses on a "bad dot", a "tap to restart" text shows up. Once the user taps the screen to restart, the original scene reloads - so they can "tap to start" again. However, if I press on a "bad" dot, the restartText doesn't show up, and the scene ends up reloading

#

it's something to do with the Touch.End and Touch.Began but I can't find a solution

lethal tusk
potent sleet
#

put a bool so user can no longer click or anything after coroutine has initiated

somber nacelle
potent sleet
lethal tusk
somber nacelle
lethal tusk
somber nacelle
#

sure, that's one way to do it. yeah

lethal tusk
#

thanks a lot

lethal tusk
# somber nacelle sure, that's one way to do it. yeah

sorry to bother
this is my json file after the first run:

{
    "Data1": {
        "highScore": 1,
        "coin": 0
    },
    "Data2": {
        "selectedCube": 0,
        "cubeList": []
    }
}

I want that cubeList to have some values in it, some bool values. the default values are true, false, false etc. is there a way to config that so I can have those values like other variables

#

instead of going that way that i change the json file in the first run

somber nacelle
#

it looks like either an array or list. so when you create the instance of the object you just create the array or list and fill it with your desired values. you do this before you serialize the object to json

lethal tusk
#

you mean where i create the array if list in the first place?

somber nacelle
#

probably? i don't really have the full context so i couldn't say for sure

#

i would personally just do it in the object's parameterless constructor (assuming this is a class not a struct)

lethal tusk
#

I'll try, thanks anyway

#

OnEnable comes first or Start or Awake?

somber nacelle
#

Awake then OnEnable are called immediately upon instantiation in that order, Start happens later

#

i do hope that question was unrelated to (de)serializing json since you shouldn't be serializing monobehaviours

lethal tusk
#

thanks

#

Im serializing some data like score and stuff that are in the GameManager script, all other sava load system are in non mono behaviours scripts
Is it wrong?

somber nacelle
#

depends, are you creating some other object that contains the data you are serializing or are you actually serializing the GameManager class itself?

lethal tusk
#

I have a struct in gamemanager script, Im serializing that

#

I make a new Objet out of that, save data in it and serialize it

#

If it effect on performance i dont really care cuz the project is not that big and this would be my first project with proper save load system

somber nacelle
#

ah lovely then you can't even use a parameterless ctor for it. why not make it a class instead?

lethal tusk
#

i mad a big mistake judging by the "lovely"

tropic quartz
#

To explain a bit, the way that waitforseconds works is that as the game reads code line by line (oversimplification maybe but ye) it will stop at that pause part until enough time passes, then runs stuff below.

It doesn't like... pause everything in that script.

So you'd probably want something to happen after that pause ends.

dawn nebula
#

Hey so I'm noticing that as a default (no material), unity will render both the front and back faces of quads/sprites. Is there a way to change this behaviour?

#

Or specify to certain sprites to only render backface/frontface?

somber nacelle
# lethal tusk i mad a big mistake judging by the "lovely"

i mean you're doing it right by (de)serializing a plain c# object, but the way you've got it set up is you'd need some other object to construct all of your default data and pass it to the object when it is created (either via parameterized ctor, or by manually assigning each property after calling the ctor). This is just fine if that's how you want to do it, i personally would prefer to just set up the default data for the object in its own parameterless ctor which would require it being a class since unity doesn't support c# 10 yet

vague jolt
#

Library\PackageCache\com.unity.2d.common@7.0.2\Path\Editor\EditorTool\PathEditorTool.cs(108,30): error CS0115: 'PathEditorTool<T>.gridSnapEnabled': no suitable method found to override

I started my unity project and i ghot this error

lethal tusk
vague jolt
#

i opened the game using an older version

wise hollow
#

Can't wait for dots raycast tutorial

lethal tusk
#

how can i find a word in a string of words?

lean sail
lethal tusk
#

find if its exits or not and returns a bool

lean sail
#

String.Contains() should be fine then

vague jolt
#
    public void save()
    {
        if(loadSaving == true)
        {
            return;
        }

        loadSaving = true;

        string save = JsonUtility.ToJson(saveJSON, true);
        File.WriteAllText(Application.dataPath + "/save.json", save);

        loadSaving = false;


    }

    GameObject structure;

    public void laod()
    {

        if (loadSaving == true)
        {
            return;
        }

        loadSaving = true;

        foreach (Transform child in transform)
       {
            Destroy(child.gameObject);
       }

        //read save file
        string save = File.ReadAllText(Application.dataPath + "/save.json");
        SaveJSON loadSave = JsonUtility.FromJson<SaveJSON>(save);

        for(int i = 0; i<loadSave.entities.Length; i++)
        {   
            foreach(GameObject prefab in prefabs)
            {
                if (prefab.tag == loadSave.entities[i].name)
                {
                    structure = Instantiate(prefab.gameObject);
                }
            }
            structure.transform.parent = transform;
            structure.transform.position = new Vector2((float)loadSave.entities[i].position.x, (float)loadSave.entities[i].position.y);
            structure.GetComponent<RotateSprite>().rotation = loadSave.entities[i].direction;
        }

        saveFile();

        loadSaving = false;
    }

THese two function save and load, but if you press the two buttons fast enoght all the entitities accumulate, what can i do to prevent it ? my bool state checking does not work..

lethal tusk
lean sail
vague jolt
lean sail
#

im not entirely sure what "entitities accumulate" means

vague jolt
#

not pressing fast

lethal tusk
#

how can I give value to a bool[] when its created? I mean when I craete it with this code:

public bool[] cubeList;

like this which we give value to a int:

public int number = 10;
idle iris
#

is there any known bug in Unity that produces white screens on nvidia gpus:?

#

seems to only render overlay uis

vague jolt
#

ok so the problem is the following, when i load the save file first i delete all the structure, then i place the new one based on the save file and then lastly i call a function that stores all the instantiated structrue in a list. The problem for some reason is that it does not remove the reference to the old structures, I know it should work because the same function is called when i destroy or place structreu but does not work when is called by the function load.

Save file generator, where the laod and save functions are, there are two save function, one to file one to the list
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/SaveFileGenerator.cs

Place structrue, here the save to list function is called right (saveFile(), sorry for terrible and confusing name)
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/ObjectPlacer.cs

Destroy strcutures, here the function is also called right
https://github.com/starlinetor/Factorio-Logic-Simulator/blob/main/Assets/Script/DeleteOnRightClick.cs

The immage is what it looks like after load is called

somber nacelle
# lethal tusk how can I give value to a bool[] when its created? I mean when I craete it with ...

either new bool[numberOfInidices] which creates an array of bools all set to false (since that is a bool's default value) or you could use a collection initializer to create the array with specific values
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
or if you create the array in the constructor for the object (assuming this is still for the object you are serializing to json) you can use a for loop after instantiating the array and assign values

knotty sun
lethal tusk
#

thanks all

vague jolt
ashen yoke
#

its says Missing, means it was destroyed

#

you just didnt clear the list

vague jolt
#

wait

ashen yoke
#

then you cleared the wrong list, or at a wrong time, or on the wrong object

vague jolt
#
        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }

This is how i destroy all the childs, is this working even if is called using abutton ?

ashen yoke
#

again, they are destroyed

#

you didnt clear the list that you show in your screenshot

#

a list wont magically know to remove destroyed objects

vague jolt
#

GameObject.Find("Structures").GetComponent<SaveFileGenerator>().saveFile();
This is called at the end of the load , this is after they are deleted

first thing the saveFile functon does is
Debug.Log("Saving");
saving = true;
structures.Clear();

I get it something is wrong here but where

ashen yoke
#

order of ops, wrong list, wrong time of clear

#

somewhere there

lethal tusk
vague jolt
#
        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }

        //read save file
        string save = File.ReadAllText(Application.dataPath + "/save.json");
        SaveJSON loadSave = JsonUtility.FromJson<SaveJSON>(save);

        for(int i = 0; i<loadSave.entities.Length; i++)
        {   
            foreach(GameObject prefab in prefabs)
            {
                if (prefab.tag == loadSave.entities[i].name)
                {
                    structure = Instantiate(prefab.gameObject);
                }
            }
            structure.transform.parent = transform;
            structure.transform.position = new Vector2((float)loadSave.entities[i].position.x, (float)loadSave.entities[i].position.y);
            structure.GetComponent<RotateSprite>().rotation = loadSave.entities[i].direction;
        }

        GameObject.Find("Structures").GetComponent<SaveFileGenerator>().saveFile();

Yes but it should wait for all the childs to be destroyed then go for instantiating the new one and then update the list

idle iris
vague jolt
#

unless it does not wait to destroy them

ashen yoke
#

you dont have to wait

#

destroy, clear, continue

vague jolt
# ashen yoke you dont have to wait

doing thisn
foreach (Transform child in transform)
{
Destroy(child.gameObject);
GameObject.Find("Structures").GetComponent<SaveFileGenerator>().saveFile();
}
does not change anything

ashen yoke
#

you are doing random actions

vague jolt
#

I was right

vague jolt
#

it waits for the end of the frame

#

meaning that all the code was exected before the game objectrs were destroyed

somber nacelle
#

correct, Destroy only queues the objects for destruction at the end of the frame. not only that but destroyed objects are not automatically removed from lists, you do have to do that yourself somewhere

vague jolt
#

you sure they get removed by default because my problem was exactly that

somber nacelle
#

do not use DestroyImmediate for this either
https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html

This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead. Destroy is always delayed (but executed within the same frame).

vague jolt
#

But they say that you should not use that function so you know a better solution ?

lean sail
#

Destroy has no idea what lists contain the object

somber nacelle
vague jolt
ashen yoke
ashen yoke
#

from the moment you marked the object for destruction you can safely assume its gone

#

for most cases

vague jolt
#

ok ok my bad i didn't get what you meant

#

i did this:

        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }

        yield return 0;

is this fine ? so iam sure that the gameobject are gone and i can save normaly.

lean sail
vague jolt
lean sail
#

wait for what though? is there code after this

lean sail
#

this still wont affect your list

quartz folio
#

yield return 0 should be yield return null if you want to wait a frame.

vague jolt
#

is there a problem with return 0 ?

#

just for curiosity

quartz folio
#

it seems like a thing you just made up

primal fern
#

hi all 👋 just wondering if anyone has advice on how to find talented freelance unity multiplayer devs. i saw #📖┃code-of-conduct redirects to official unity forums, but honestly those posts (and their responses) are uninspiring

we're a VC-backed startup and have the capital, building out some really interesting stuff

vague jolt
vague jolt
lean sail
#

because now all the game objects are just null, but the list still hasnt changed

vague jolt
quartz folio
vague jolt
primal fern
#

fiverr quality can vary widely, we're looking for more proven talent and paying more for the right collaboration

which channel here on discord is more appropriate for getting this advice?

vague jolt
#

but indeed null makes more sence

vague jolt
#

just kidding

#

i am stupid

#

i just read the description

quartz folio
primal fern
#

thanks @quartz folio for the record i'm not trying to find someone here, but rather getting advice from engineers here who know of the best channels through first hand experience

#

for instance, if you told me "Unity job forums are shit, nobody good checks those" then that would be valuable info

quartz folio
#

Nobody checks the forums, nobody checks large nebulous platforms

lean sail
void basalt
quartz folio
#

Continue this in #💻┃unity-talk seeing as it's cross-posted there anyway (please do not crosspost).

primal fern
#

thanks @lean sail i am pretty unconventional, and prefer to seek out the talent rather than sift through people applying to our job post. i have moved the discussion to #💻┃unity-talk because i'm guessing that's the more appropriate channel

#

tysm all 🙏

primal fern
quartz folio
#

It's fine, just continue the convo there if anyone wants to, but it's pretty much been answered imo

novel kayak
somber nacelle
dense tusk
#

any of you lads have advice on how i can create an object moving system where i can pick up objects without them clipping through other objects, or spazzing out when touching another object? i have an idea on how i can have it keep a target position and keep it's rotation relative to the camera, but i don't know how to go about working with collision.
my research has mentioned i need to use velocity with rigidbody physics, but i don't understand how to implement that. the closest example i could find was a little difficult to follow

earnest hare
#

Hi, I am going to use unity iap for the first time. I heard that the codeless IAP is broken, is that right? so i have to implement the iap via coding?

vague jolt
#

there are many setting depending what you want to do but it should still work out of the box even if not in a hoptimal way

lean sail
#

you'll still run into issues with it spazzing out if you do that, especially if you are trying to keep the object at a target position

lean sail
dense tusk
#

i do. my objective is to have it try to correct itself to a target position & rotation, while getting altered by anything that gets between them, such as picking up a book and trying to drag it on a table, but getting hung up on an immovable object

#

and then i reckon if the distance to correct is too high it will just stop trying and fall, and then the selection will be null, but i can figure out that part myself

vague jolt
lean sail
vague jolt
#

you keep the actuall object in a fixed position and then move the sprite around to not clip

#

or you could use forces to keep it in place, this way the object would not clip because if a force makes it collide on a structure the force does nothing, it would also look a bit more realistic maiby

lean sail
#

separating the actual object and visual sounds horrible for this..

#

honestly i dont know what you mean to use animations for this

dense tusk
#

i’m not using sprites anyways. this is being done in 3D

vague jolt
#

sorry i just use 2d i don't know the name for 3d

#

like what you want to do is something like slime rancher ?

dense tusk
#

lol all good. appreciate the suggestion regardless

vague jolt
#

like the gun that sucks stuff and keeps it there ?

dense tusk
dense tusk
void basalt
vague jolt
lean sail
lean sail
vague jolt
#

or another thing you could do is the same that some fps do for guns

#

you render the cube separated from the world in such a way that it does not appear to clip

void basalt
#

that's still going to look very weird

vague jolt
#

even if is tecnically clipping

vague jolt
lean sail
#

thats going to be really annoying to setup, especially since they want it to be colliding with objects so its not* going to be clipping with rigidbodies

void basalt
#

The best way is to just to simply point the velocity wherever it needs to go

#

I'm almost certain this is how gmod does it anyways

#

it can be created with a basic damper system. Far away from the point? More velocity. Close to point? Less velocity

lean sail
#

thats also why i suggested spring joints, but maybe spring joint would have unintended results

#

like if it goes out of bounds, the force might go really high

vague jolt
#

i feel like burt idea of just moving ity with a force/velocity to a fixed point seems the easiset to implement

lean sail
dense tusk
lean sail
dense tusk
#

ohhh you sure can determine the direction with addforce can’t you

lean sail
#

you add a force in a direction yes, which changes the objects velocity. The forcemode* you use will have a different effect

dense tusk
#

period. that might be just what i need to look at. i’m so slow i’ve been struggling with that concept for days and it’s like a day one function that i forgot 😩

void basalt
#

if you want something snappy

weary rose
#

does anyone know how I can make it so that when i switch cameras, the player doesn't doesn't like whip around? What i mean is, when the player is in the free look camera mode and the camera and player model are facing in oposite directions. then when the player switches to the backview, the player model faces where the free look camera was facing before

lean sail
#

just ask your question here, no ones gonna give 1 on 1 lessons for free

dense tusk
#

@lean sail @void basalt just came back to say thanks for the input. y'all both pointed me in the right direction and i'm much closer to getting what i want now

#

asking questions is how you learn lad

lean sail
#

re-read my message lol, just because u want to learn doesnt mean ppl will teach u for free

dense tusk
#

you're asking someone to teach you

#

not a question

lime widget
#

This is how my character looks (the 2 rectangles above are the leg formed from 2 parts. I will multiply the leg after I finish this). How can I add bones to this?

lean sail
#

it should be called "2d rigging"

lime widget
#

I tried to look for a tutorial like this but they all are using sprites. I am using only game objects. Sorry about the code part.

rain minnow
#

a SpriteRenderer is a component attached to a GameObject. it has a sprite property where a 2d sprite is placed . . .

gentle rain
#

Could I get some help with this

my hand Model is supposed to look like this when I pick up a Thompson Mag but when I try to pick it up it looks like

#

That is with my hand just normally straight

#

and once I let go it goes back to normal

sweet current
#
unborn pier
#

linear regression

lean sail
#

the math really isnt hard, considering its all solved already. Just a matter of taking the algorithm

lusty dune
#

There should be a math function that makes a slope like that on graph, use it and add random range...

unborn pier
#

How do I post code

#

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

unborn pier
#
    {
        // Calculate the centroid of the dots
        Vector3 centroid = Vector3.zero;
        foreach (Vector3 dot in dotsList)
        {
            centroid += dot;
        }
        centroid /= dotsList.Count;

        // Calculate the sums of products for the covariance matrix
        float sumXX = 0f;
        float sumXY = 0f;
        float sumXZ = 0f;
        float sumYY = 0f;
        float sumYZ = 0f;
        foreach (Vector3 dot in dotsList)
        {
            Vector3 deviation = dot - centroid;
            sumXX += deviation.x * deviation.x;
            sumXY += deviation.x * deviation.y;
            sumXZ += deviation.x * deviation.z;
            sumYY += deviation.y * deviation.y;
            sumYZ += deviation.y * deviation.z;
        }

        // Calculate the covariance matrix
        Matrix4x4 covarianceMatrix = new Matrix4x4(
            new Vector4(sumXX, sumXY, sumXZ, 0),
            new Vector4(sumXY, sumYY, sumYZ, 0),
            new Vector4(sumXZ, sumYZ, dotsList.Count, 0),
            new Vector4(0, 0, 0, 1)
        );

        // Calculate the eigenvalues and eigenvectors of the covariance matrix
        covarianceMatrix = covarianceMatrix.inverse;
        Vector3 eigenvalues;
        Matrix4x4 eigenvectors;
        covarianceMatrix.Diagonalize(out eigenvalues, out eigenvectors);

        // The eigenvector with the smallest eigenvalue represents the direction of the best-fit line
        Vector3 bestFitDirection = eigenvectors.GetColumn(0);

        // The centroid represents a point on the best-fit line
        Vector3 bestFitPoint = centroid;

        // Now you can use the bestFitDirection and bestFitPoint to visualize or further utilize the best-fit line
        Debug.DrawLine(bestFitPoint - bestFitDirection * 100f, bestFitPoint + bestFitDirection * 100f, Color.red, 10f);
    }```
fervent furnace
#

linear regression will give you the line that fits input points..

unborn pier
#

Just populate with your list of 3d points

lusty dune
#

But lot simplistic

unborn pier
#

but like this

lean sail
unborn pier
#

no

#

I don't even know what a eigenvalue or covariance matrix is

lean sail
#

oh..i was gonna say i was impressed someone could be confident in their lin alg skills this much

lean sail
unborn pier
#

I take lin alg next semester so maybe I'll understand a portion of it

lean sail
#

well i understood it, then upper year courses made it more complicated

fervent furnace
#

i already forgot all topics on stats i studied

brazen reef
#

quick question which i'm sure if obvious to those who know, i'm playing around with unity to learn and i'm working on learning raycasts, and my current issue is that dispite my best attempts, it doesn't seem to be registering:

 void JumpStart(InputAction.CallbackContext value)
    {
        Debug.Log("Jump Pressed!");
        
        RaycastHit hit;
        
        if (Physics.Raycast(
                transform.position,
                scanDirection,
                out hit,
                jumpScanDistance,
                0
            ))
        {
            Debug.Log("Did Hit");
            
            if(hit.transform.tag == "ground") {
                Debug.DrawRay(
                    transform.position,
                    scanDirection,
                    Color.green,
                    5
                );
            }
            else
            {
                Debug.DrawRay(
                    transform.position,
                    scanDirection,
                    Color.cyan,
                    5
                );
            }
            
            Debug.Log("Raycasted");
        }
        else
        {
            Debug.Log("Did not Hit");
            Debug.DrawRay(
                transform.position,
                scanDirection,
                Color.blue,
                5
            );
            Debug.Log("Raycasted");
        }
    }
sweet current
#

You know that something is not easy to understand when the people who use it don't find a better translation than half-german. ( eigenvalue /eigenvector )

lean sail
#

(i know, just seeing if they know)

unborn pier
#

oops

brazen reef
#

aka, da default lol

lean sail
#

double check i guess if your ground is really on default, and visualize how far the ray is going by doing

Debug.DrawRay(transform.position, scanDirection * jumpScanDistance, Color.green, 5);
brazen reef
#

at least from what jetbrains is telling me lol

quartz folio
#

Please just read my resource so you understand what a layermask is

brazen reef
#

no green either with the test for whatever reason

brazen reef
quartz folio
brazen reef
#

maybe i'm missing something, but yee

lean sail
#

0 should work if its the default layer right? although i agree still should setup the layer properly
im dumb, its 3am dont judge me

brazen reef
quartz folio
#

That is not a bitmask, that is a layer index

#

you are not bitshifting based on that layer index, you are just passing 0

brazen reef
#

then why are they both called layers??

quartz folio
#

One is a layer mask, one is a layer

#

your mask looks like this:
00000000000000000000000

#

All bits are 0, ie. there are no active layers in your mask.

fervent furnace
#

you need something likes: (1<<index1)|(1<<index2)

quartz folio
#

Again, my resource explains this, how to make them, and also has another resource linked at the bottom that goes into them in extreme detail

brazen reef
#

okay, attempting to call it via a bitshift by pre-claiming it as a var seems to be giving similar results:

[SerializeField] LayerMask layerMask = 0<<3;
quartz folio
#

[SerializeField] LayerMask layerMask; and set the mask in the inspector

lean sail
#

0 << 3 is not doing anything also

quartz folio
#

bitshifting 0 will produce 0.

fervent furnace
#

0<<3=0b000000....

brazen reef
#

tbh never heard the concept of bitshifting so all completely new to me

quartz folio
#

good thing there was a resource explaining bitshifting on the very page I continue to talk about

mystic yoke
#

I wonder if @quartz folio has something that talks about bitshifting? 🤔

brazen reef
fervent furnace
#

you can image that you are puttin a one (or zero) at some positions in 32-bits int

#

eg 1<<2==0x0000 0004, 0x is hexadecimal form

quartz folio
brazen reef
#

i'm not trying to ignore that, more just it's talking about stuff in an abstract way that i don't follow well. it's like saying
"an engine is like a stick of tnt in a metal box", abstract enough they make sense, but the page itself fails to connect any dots for me to be more specific

analog relic
brazen reef
analog relic
#

Yup pretty much

brazen reef
#

0010 = 4 and all that

lean sail
#

0100 but yes

brazen reef
quartz folio
#

big endian, little endian, programming is pain

brazen reef
#

something about left most being the input and the system counts up from their but i digress, my brain is a soup of other peoples knowledge lol

lean sail
#

oh, doesnt really matter. theres least and most signifcant notation

brazen reef
#

okey, well, back to the og issue lol, here's now where i'm still sorta just spinning wheels or what have you because despite selecting that specific layer, and making sure the ground is that layer, it seems to be failing to register a hit

#

lines should be green/cyan if something is hit

#

ah, got it, simply issue with the ui scan distance being set to 0

#

well, thanks for everyones help, apprecate it and the education!

lean sail