#archived-code-general

1 messages ยท Page 80 of 1

shell scarab
#

sigh quaternions here I come

plucky karma
#

The way I understood quaternions is that there's two set of angle, and two set of distance. The angle helps rotate initially, then the distance tells you how far you are on that angle. Then repeat for the second angle, which gets rid of the third dimension entirely (effectively removing gimbal lock)

shell scarab
#

I'm going to be honest

#

that doesn't help me understand them more

#

I'm getting more of a feeling for using them though.

plucky karma
#

It's complicated, have you try using TransformPoint?

shell scarab
#

yes it happens with TransformPoint too

plucky karma
#

What about LookAt()?

shell scarab
#

yup

#

๐Ÿฅฒ

#

it's fine. i've been dabbling in Quaternions a little bit. I don't need to fully understand them just yet, I just need it to work... i can understand them later

plucky karma
#

Quaternions are fun and powerful if you really understand. It's like a matrix4x4.

odd lotus
#

So i'm just trying to change color of a 2D Sprite Renderer, and then here's what happens:
They turn invisible.

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Teleporter : MonoBehaviour
{
    public GameObject opposingPortal;
    public bool ChangeColor;
    public Color32 colorToChangeTo;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player") {
            other.gameObject.transform.position = opposingPortal.transform.position;
            if (ChangeColor) {
                other.gameObject.GetComponent<SpriteRenderer>().color = colorToChangeTo;
            }
        }
    }
}

Code for refrence.

#

oh wait i'm stupid

#

there's something about the alpha

fallen hare
#

hey, because I'm making an Interact script and I don't know why it shows an error

tropic sleet
tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

fallen hare
#

i did but the error is still there

somber nacelle
fallen hare
#

ok

#

my vsc not detected problems

somber nacelle
#

then it isn't configured

fallen hare
#

I have configured it now and still nothing

somber nacelle
#

just configuring it won't magically fix the issue. it will just show you where the issue is.

fallen hare
#

**using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Interact : MonoBehaviour
{
public GameObject col;
public GameObject text;

void Start()
{
    text.SetActive(false);
}

public void OnTriggerEnter(col)
{
    text.SetActive(true);
}

}** Code i dont know where is the problem just error

somber nacelle
#

configure vs code so it will show you where the issue is

#

if you cannot get vs code configured then consider switching to visual studio which is much easier to configure and is actually still supported

fallen hare
#

what?

somber nacelle
#

which part of that did you not understand?

quick kindle
#

hah was it @leaden ice and @heady iris i was talking with about the mapmagic2 issue? praetor your suggestion to reach out to denis worked - funny update to the story - so i reached out to denis asking if he had any tips - in the meantime, i figured out how to write a custom generator node for mm2, and had a hacky solution that just used it to write to a scriptable object - but then denis got back to me, we exchanged some emails, and he said that spline output node should be working? i pointed out where it wasn't, he apologized and sent a new (working) version of SplineOut, lol

somber nacelle
#

you know what the word "configure" means, yes?

fallen hare
#

yea

somber nacelle
quartz folio
#

(click the link that says VS Code and follow all of the instructions)

fallen hare
#

ok

heady iris
#

someimes (especially if you paid for it!), you can just say hi

steady moat
# fallen hare code

OnTriggerEnter should be public void OnTriggerEnter(Collider other) . You are missing the declaration of the type of your parameter.

barren imp
#

hey
anyone here know about MFPS or ulogin pro???
pls dm me if u know

rough sorrel
#

Hi. One question, does anyone know if there's a way to select a gameobject at runtime if it doesn't have a gameobject? Like, select it as if it was in the editor but do it in a build

remote halo
#

can anyone hleep me maek a enemy in my game cuz i am not good at coding and like idk almost anything about it and im just using chatgpt to do it and i cant find any good enemy tutorial tings

#

welp ig nobody can helep me atm

somber nacelle
remote halo
#

ko

#

welp shit guess im gonna go back to trying to maek it with chatgpt

somber nacelle
#

good luck. don't expect help with your AI generated code here though

tepid charm
#

Hey, this might be a bit of an abstract problem but I'm making an RTS and I want to make it so that when you set a unit to attack another unit, it will automatically find a a soldier to target while staying in formation. Here, for example, each soldier will be assigned to a target with an index across from it, which is pretty easy when dealing when units of the same size (and using dot products to check if the order should be reversed)

#

But the problem arises when you try doing this with two units of different sizes

#

with the current approach, they will end up crossing each other

#

so this is what happens with units of the same size

#

and this is with different sizes

#

sorry for the spam

#

but I'm looking for a way to have them find a target directly across (or at least one that doesn't require crossing)

#

each unit has values for unit size, depth and length

fresh moss
#

Using Buttons with both Sprite Swap and keyboard input, is this possible?

tepid charm
hard estuary
# tepid charm that could work, though I'd imagine it would be quite a heavy calculation for la...

Yeah, it would be quite expensive for huge squads. I suppose it could be sped up by somehow dividing the squad into subsquads. If the performance was an issue, you could try some quadtree implementation, so you could check only units from a particular map area.

If you want a simplified approach, I would suggest calculating targets only for corner soldiers, and then try to set other targets analogically. If a unit from position x1, y1 targets a unit from position x2, y2, then a unit from position x3, y3 would probably want to target a unit from position x3-x1+x2, y3-y1+y2. The results should be decent as long the formation is regular - any bigger noises could make targeting look noisy.

tepid charm
#

thanks!

real ivy
#

hi : D

#

maybe

#

just maybe

#

i hate matrix in C#

#

is there any easy way to multiply 2 matrix who isn't 4x4?

simple egret
hollow knot
#

Does any one know how i can make a flashlight type of light in a top down 2D game so that it wont render bojects if they are outside of thie flashlight making it almost pitch black

cobalt wave
#

matrices in C# are still just matrices

#

see how matrices work in mathematics and you'll stop hating "C# matrices"

cobalt wave
#

you could try using the experimental 2D lighting that comes with URP

plucky karma
cobalt wave
# hollow knot Does any one know how i can make a flashlight type of light in a top down 2D gam...

or https://www.youtube.com/watch?v=rQG9aUWarwE this
note: it's in 3D, but I know it can be converted to work with 2D because I did so in one of my projects

In this miniseries (2 episodes) we create a system to detect which targets are in our unit's field of view. This is useful for stealth games and the like.

Source code + starting file:
https://github.com/SebLague/Field-of-View

Support the creation of more tutorials:
https://www.patreon.com/SebastianLague
https://www.paypal.me/SebastianLague

โ–ถ Play video
timid meteor
#

I am trying to setup a VR script that looks in a certain direction and if it hits a box collider in layer 8 that it will print out Looking at Watch

#

The problem atm is if I am not looking at the watch it will still say looking at watch. Anyone know why?

cobalt wave
#

is the watch on a wall?

#

or is it staring into nothingness

timid meteor
#

so no it's on the player's hand

#

this is vr

cobalt wave
#

hmm

#

myb i should inspect the code a bit more lul

#

also, why do you 1 << 9 if you want the 8th layer?

timid meteor
#

// Bit shift the index of the layer (9) to get a bit mask

cobalt wave
#

also

#

uhhh

#

it's because you say "else, debug.log("Looking at watch")"

#

it will debug the same thing no matter what

timid meteor
#

omgosh

cobalt wave
#

it happens

timid meteor
#

XD

#

Ah well I still found a slight issue

timid meteor
#

could hit.distance be the cause?

plucky karma
#

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

timid meteor
#
    void Update()
    {
        // Bit shift the index of the layer (9) to get a bit mask
        int layerMask = 1 << 9;

        // This would cast rays only against colliders in layer 8.
        // But instead if we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
        //8layerMask = ~layerMask;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            //Vector3 Position = new Vector3(transform.position.x + 5, transform.position.y, transform.position.z); //Sets position on where inventory spawns
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Looking At Watch");
            //GameObject instance = Instantiate(InventoryTest, Position, Quaternion.identity);
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("not Looking At Watch");
        }
    }
plucky karma
#

So many comments in your Update() method. If your layerMask is never going to change anytime during your game runtime, might as well cache the result and use it as a reference.

#

Or make your LayerMask an inspector value to change/adjust.

sly slate
#

I'm instancing a bunch of game objects at runtime. Is it possible to make a prefab of the scene(partof) and still keep the instanced prefabs link intact?

timid meteor
timid meteor
timid meteor
plucky karma
timid meteor
#

set it to layer 9 and called it watch

plucky karma
#

isn't transform.TransformDirection(Vector3.forward) the same as transform.forward?

maiden fractal
cobalt wave
timid meteor
cobalt wave
#

it's not needed

#

you can use both

timid meteor
cobalt wave
#

well then I'm 99% sure it collides with the camera's collider

timid meteor
#

hmm if it's on the camera wouldn't that not be part of the objects it hits?

cobalt wave
#

make sure to shoot the ray outside the camera's collider, or do Physics.IgnoreLayer or something like that and ignore the camera

plucky karma
#

the layerMask would've omit the collision..

#

Does the watch have collider as well?

timid meteor
cobalt wave
#

actually, it almost never did that for me

timid meteor
#

but it can't have a rigidbody because that messes with the VR hands

sly slate
# plucky karma Yes?

@quaint pine okay, I hoped so... How ?
if I create a gameobject by instantiate and reference a prefab it looses its reference once its in the scene

plucky karma
#

It should work... You have debug.DrawRay, whatwhere does it hit?

timid meteor
#

yes when I start the game on unity I can see it move around but I don't see it in the head set

#

so it aims and changes color

#

but doesn't activate for some reason

plucky karma
gray mural
#

hey, does anybody know how to create the instance of GameObject without Instantiating it and without changing the original prefab?

private void SpawnEnemy()
    {
        Vector3 currentPos;

        while (true)
        {
            currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));

            GameObject enemy = enemyPrefab; // need to change this one

            enemy.transform.position = currentPos; // or/and this one

            Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;

            Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
            Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
            Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
            Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);

            if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
        }

        Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);

        bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
    }
cobalt wave
#

what

plucky karma
#

We look at your code that only tell us that the raycast hit hits only your watch, but when you say "activate" what do you mean? Are you trying to invoke something on your watch?

timid meteor
cobalt wave
timid meteor
#

is that when the player looks at the watch a hud will appear

cobalt wave
#

yes but

#

what do you mean

#

by activate

plucky karma
cobalt wave
#

what does activate at this moment

timid meteor
#

what I am trying to do right now is just get it to say debug.log("looking at watch")

#

"Looking at watch"

cobalt wave
#

then just Debug.Log(hit.gameObject);

gray mural
cobalt wave
#

so we can see what it hits

cobalt wave
timid meteor
cobalt wave
#
GameObject go;
rocky jackal
#

i have no lcue how this list error is connected to me invoking an event, i need help

gray mural
timid meteor
#

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

sly slate
#

@quaint pine The problem occurs at the moment I instansiate the objects that will become nested in a parent prefab later. The child objects are all named (clone) in the hierarchy and has lost their references.

timid meteor
cobalt wave
#

is what i meant

gray mural
timid meteor
#

ah ok

simple egret
cobalt wave
sly slate
#

Ideally I would want them intact with the prefab linkage + a bunch of overrides

gray mural
cobalt wave
#

and how does this change the prefab?

plucky karma
rocky jackal
#

and there arent too many nor to less

gray mural
cobalt wave
gray mural
# plucky karma Wait... you're not calling Instantiate?

look:

private void SpawnEnemy()
    {
        Vector3 currentPos;

        while (true)
        {
            currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));

            GameObject enemy = enemyPrefab;

            enemy.transform.position = currentPos;

            Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;

            Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
            Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
            Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
            Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);

            if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
        }

        Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);

        bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
    }
plucky karma
#

Instantiate creates a copy. You can't access information within prefabs if they're not initialized, otherwise you're directly modifying the "source" prefab object.

simple egret
timid meteor
gray mural
plucky karma
sly slate
#

exactly ... I don't really want a copy. I would like the reference intact

gray mural
sly slate
#

like if I would drag the prefab into the scene

#

I want to do that with code

rain minnow
gray mural
cobalt wave
timid meteor
gray mural
#

create UIDocument for example and create gameObject here

cobalt wave
#

that's because you didn't set up the layers correctly then

timid meteor
#

but the weird part is it's changing colors

cobalt wave
#

are you 100% sure that the watch is on the right layer

rocky jackal
gray mural
cobalt wave
gray mural
simple egret
ancient sail
#

hey everyone, im currently working on a platformer, but there is one thing that does not work. In editor everything works perfectly, but as soon as I build the project some of values feel wrong so i cant make some of the jumps

cobalt wave
#

the fps in the editor is infinitely higher than in the build version

timid meteor
# cobalt wave can you resend the code, the newest version
    // Update is called once per frame
    void Update()
    {
        // Bit shift the index of the layer (9) to get a bit mask
        int layerMask = 1 << 9;

        // This would cast rays only against colliders in layer 8.
        // But instead if we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
        //8layerMask = ~layerMask;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            //Vector3 Position = new Vector3(transform.position.x + 5, transform.position.y, transform.position.z); //Sets position on where inventory spawns
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Looking At Watch");
            //GameObject instance = Instantiate(InventoryTest, Position, Quaternion.identity);
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log(hit.transform);
        }
    }
cobalt wave
#

or is it the other way around I don't remember

cobalt wave
#

or else you'll have unpredictable results

sly slate
#

I think what I want to do is only possible inside the editor and not at runtime

gray mural
ancient sail
#

I usually do them in fixedUpdate but i must have messed up with timed events

cobalt wave
timid meteor
#

I think I may have found the issue

#

brb

cobalt wave
#

aight gl

plucky karma
#

Time.deltaTime becomes Time.fixedDeltaTime when used inside FixedUpdate() method.

cobalt wave
#

yes

sly slate
#

Instantiate can only create clones not references to prefabs ๐Ÿ˜ฆ

gray mural
#

yes

cobalt wave
#

yea

sly slate
#

bummer

rain minnow
cobalt wave
#

how is that a problem exactly?

gray mural
#

how to I then create clone without Instantiate method?

rain minnow
#

It's used as a template . . .

cobalt wave
#

why do you not want to use the Instantiate method so much

rain minnow
#

What exactly are you trying to do?

#

Do you need an actual GameObject or a MonoBehaviour class. You can create instances in memory with c# classes . . .

gray mural
#

I have written it before

#

what?

#

how?

cobalt wave
#

what exactly do you need though

gray mural
#

I have written it few times

cobalt wave
#

this is starting to sound alot like you need ScriptableObjects

cobalt wave
sly slate
#

my scenario is a bit complicated.. I got an ingame-editor that can create levels by using instantiating prefabs... Now I want to load up the game in the editor, create a map. Grab an entire map or part of a map in the hierarchy and create a prefab of it (this works fine) but all the items inside the new prefab are only clones.. would be nice if the prefab references where intact and only a couple of overrides applied to them

cobalt wave
#

I'm so confused, do 2 people have the exact same problem? lmao

sly slate
#

seems like it ๐Ÿ˜„

cobalt wave
#

I mean, why would it be nice?

#

it seems to me like you have it working

sly slate
#

then I could change a chair or something.. then it would change the chair prefab.. and update all the rooms that use the chair

cobalt wave
#

the prefab references are intact wdym

#

yes you can already do that

#

just change the chair

#

in the editor

sly slate
#

If I had done this in the editor.. it would work. But the problem is that I am creating the world using my own in-game editor

#

so I fire up my in-game editor.. grab my room that i want prefabed. But the chairs and stuff are all just clones by now

#

since they are create using Instantiate

cobalt wave
#

I think you need a "Load" function

sly slate
#

yes... that's a good idea. I guess I could write an editor script to use my existing load function

#

๐Ÿ˜„

plucky karma
#

Wouldn't it be easier if you'd just create a prefab of the level, so that you can just drag and drop into your scene?

cobalt wave
#

it appears they don't want that functionality though

rain minnow
gray mural
# cobalt wave great, what

I need to create enemyPrefab in the Scene on the the hexagon, not rectangle. So I have (float min, float max) x and z positions (tuples) to create like if it's rectangle.
But to avoid creating enemyPrefabs where they just fall nowhere, I do check if they are on the floor with Physics.Raycast with while loop, if they are, I just break that while loop and create enemy on that nice position, where they do not fall.
The Raycasts are gone from enemy's bounds, but to get those bounds, I should GetComponent<SphereCollider>() of enemyPrefab. To do it I need to Instantiate it. But? It instantiates in the scene then. To avoid that I just create GameObject instane, but this also changes original enemyPrefab.
And now the question: How can I do the same without changing original enemyPrefab position?

cobalt wave
#

yes

#

Instantiate it

gray mural
cobalt wave
#

you are doing something secondary that changes the prefab's position

plucky karma
#

Ideally, if you know that the enemy must spawn on hexagon shape, then I would create a manager to keep track of all existing hexagon shape, that the enemy can spawn on. Then your manager would expose method implementation to receive coordinate, which will check any existing hexagon shape that matches that coordinate and spawn it. Otherwise, skip.

cobalt wave
#

ah

#

I see

#

@gray mural you need to change the position after you instantiate the object

#

sort of like this

cobalt wave
#

GameObject go = Instantiate(prefab);

#

no

#

just

cobalt wave
#

do the other stuff

#

after that instantiation

#

everything you do in the while loop

gray mural
cobalt wave
#

do after

#

sees what

#

it won't see it

gray mural
#

enemyPrefab

cobalt wave
#

it can't see in a frame

#

even less

#

just

plucky karma
#

Disable the gameobject after you spawn it, so that the player can't see it?

cobalt wave
#

it's the same

sly slate
#

@quaint pine yes.. that is pretty easy, the problem comes later if I want to update some item inside the room.. it would have lost its reference

plucky karma
#

How would you update the item if it didn't have reference initially???

#

You'd only lose reference if you override the reference. Then that's a dangling reference problem.

sly slate
#

yes, that's why I was asking about how to Instantiate without making a copy ๐Ÿ™‚

cobalt wave
#
private void SpawnEnemy()
    {
        Vector3 currentPos;

       

       GameObject enemy = Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);
       while (true)
        {
            currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));

            enemy.transform.position = currentPos;

            Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;

            Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
            Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
            Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
            Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);

            if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
        }

        bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
    }
#

didn't proofread it

#

but this is the logic

#

it's exactly the same

#

except it does what you want it to do

#

you could also put this line GameObject enemy = Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform); inside of the while loop

plucky karma
#

Needs enemy.SetActive(false); until it finds a place to stand on.

gray mural
cobalt wave
#

BUT IT WONT BE THERE

#

do you understand

#

how unity works

gray mural
#

ah

cobalt wave
#

and how pc's work

#

the entire script

#

is swept

#

from top to bottom

#

in one frame

#

you won't see the enemy spawned at 0,0,0

#

the while loop has to finish in the frame and if it doesn't, you get a frame drop, simple as that

#

fps drop*

gray mural
#

I just gonna let it as it is, I sure do not need enemyPrefab's position

cobalt wave
#

because it takes longer to finish the frame

gray mural
#

The player does see that frame

cobalt wave
#

no

#

they

#

dont

lucid crow
#

Hey guys i'm new here ๐Ÿ˜› i was trying to follow this to save data instead of using playerprefs https://www.youtube.com/watch?v=aSNj2nvSyD4 the project im working on will be my first completed one its very small lol im still learning.. anyways the problem im having is ArgumentException: Empty path name is not legal. followed tutorial just to see if i could get it working but... yea

In this Tutorial, we're going to make SAVING DATA GREAT AGAIN! Using the JsonUtility class to save data in the JSON format is going to be a breeze and it's just a good idea to do so!

== WRITTEN TUTORIAL ==
Blogpost: https://url.kaupenjoe.net/yt11/blogpost

== ASSETS & DOWNLOAD LINKS ==
GitHub Repo: https://github.com/Tutorials-By-Kaupenjoe/Sav...

โ–ถ Play video
cobalt wave
#

it gets spawned at 0,0,0
then it gets manipulated

gray mural
#

ok I gonna prove it to u bro

cobalt wave
#

what the player sees? whatever happened after the manipulation!

#

please do

gray mural
#

ah no

#

I won't

#

because I have 200+ fps there and I cannot see it

cobalt wave
#

no

#

but because

gray mural
#

but if I had 50 fps, then =>

cobalt wave
#

you don't understand how processors work and how they carry out instructions

#

the entire script

#

is done in one frame

#

meaning that if the last bit of the script "moves" the enemy, that's where the enemy is going to be

#

this is so painful to explain and i gotta get ready so bye, can someone else take over

hexed pecan
lucid crow
#

its a flash blink of an eye

gray mural
#

really?/

#

oh, I did not know that

cobalt wave
#

i'm physically hurting after this exchange, I'm glad you figured it out tho!

#

thx osmal blushie

lucid crow
#

so anyone here good with saves using json? its for a small first project i just dont want to use playerprefs

gray mural
lucid crow
#

they have a bad rep

hexed pecan
cobalt wave
#

lmao

gray mural
#

nope

plucky karma
cobalt wave
#

I think it's a language barrier

hexed pecan
#

I was saying what Thicc was saying too

cobalt wave
gray mural
small hemlock
#

so uhhh

cobalt wave
small hemlock
#

im getting nullreferenceerrors on only the game build

#

and not in the editor

small hemlock
#

it seems to be failing to get any of the components that should be there

plucky karma
#

How did you learn about C#? @gray mural

small hemlock
#

and since im getting like 20000 errors i cant read them all

gray mural
lucid crow
#

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

plucky karma
lucid crow
#

ArgumentException: Empty path name is not legal. followed tutorial just to see if i could get it working but... yea

gray mural
small hemlock
#

i can remember how to attatch profiler

simple egret
lucid crow
#

so the path = on line 25 doesnt set them?

simple egret
#

It does, but as path is empty, it sets an empty string

#

Look at the tutorial. They might do SetPaths(); in Start or something, you missed it

lucid crow
#

okay

lucid crow
#

new to programming i just don't want to learn bad practices

#

ik json files can be tampered with but I dont care as long as i can save what i need to for bigger projects thanks for the help ๐Ÿ™‚

gray mural
#

i have entered infinite while loop๐Ÿ’€๐Ÿ’€

#

see ya after reloading computer

rain minnow
#

Just stop the task . . .

small hemlock
#

ok so the issue seems to be that

#

the component can not be accessed from another script for some reasons

#

it can be accessed from the script in the gameobject the component is in

heady iris
#

well, how are you trying to retrieve the component?

small hemlock
#

i am using gameobject.getcomponent

heady iris
#

show your code.

small hemlock
#

enemyhitboxes= enemyylist.transform.Find("hitbox").GetComponent<BoxCollider2D>(); one of the many examples that brings an error

#

this only happens in build mode not in editor

#

i think its an access issue

#

as in the scripts cant access anything in another gameobject for some reason

rustic ember
#

Is there an easy way of resetting a ScriptableObject to the starting values?

rustic ember
#

I mean in code

cold parrot
#

Same

rustic ember
#

?

cold parrot
#

Without the right click

rustic ember
#

this.Reset() ?

#

Does that reset a script?

hexed pecan
#

Looks like its for MonoBehaviour only

cold parrot
#

It sets all serialized fields to their default values or runs whatever overrides youโ€™ve implemented

rustic ember
#

Nice

rustic ember
rustic ember
#

Great great

#

Thank you all ๐Ÿ™

somber nacelle
#

however i'm not sure if calling it manually is going to reset it's serialized fields

hexed pecan
#

So idk if calling it manually would do anything

cold parrot
#

Btw, you should not be overwriting serialized values. So in a properly implemented SO, this wouldnโ€™t come up

hexed pecan
cold parrot
#

you would have to implement the reset ofc

hexed pecan
#

Yeah I dont know if manually resetting every member in the code is what hes asking for

cold parrot
#

maybe like this ```cs
public class MySO : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField] private float foo;

    public float Foo { get; set; }

    private void Reset()
    {
        Foo = foo;
    }

    public void OnBeforeSerialize()
    {
    }

    public void OnAfterDeserialize()
    {
       Reset();
    }
}
knotty sun
#

Just use Resources.Load to reload the SO

fickle vigil
#

Update: it was actually the provided default settings like โ€œthresholdโ€ that were stopping it from working. Which explains why I got zero errors when debugging it in VS. Anyway, I just messed around with the settings, despite what the included PDF, instructed and voilร ! thank you for your help yesterday also @somber nacelle @simple egret ๐Ÿ™

gray mural
#

Why do I have infinite while loop?

private void SpawnEnemy()
    {
        GameObject enemy = Instantiate(enemyPrefab, Vector3.zero, spawnRot, enemiesDocument.transform);

        while (true)
        {
            enemy.transform.position = new (TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));

            Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;

            Vector3 topLeft = new(bounds.min.x, bounds.min.y, bounds.max.z);
            Vector3 topRight = new(bounds.max.x, bounds.min.y, bounds.max.z);
            Vector3 bottomLeft = new(bounds.min.x, bounds.min.y, bounds.min.z);
            Vector3 bottomRight = new(bounds.max.x, bounds.min.y, bounds.min.z);

            if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
        }

        bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
    }
#

I have done as guys before suggested me

somber nacelle
#

because you typed while(true) and your if statement at the bottom is never true to break out of the loop

gray mural
#

why is it never true?

#

it was true in my previous version of code

somber nacelle
#

well when could the bounds on the enemy sphere collider change during that loop?

#

since this is not a coroutine that is yielding no other code besides this loop is running for the duration of the loop

gray mural
#

this one worked very well:

private void SpawnEnemy()
    {
        Vector3 currentPos;

        while (true)
        {
            currentPos = new Vector3(TupleRange(spawnPos.x), spawnPos.y, TupleRange(spawnPos.z));

            GameObject enemy = enemyPrefab; // need to change this one

            enemy.transform.position = currentPos; // or/and this one

            Bounds bounds = enemy.GetComponent<SphereCollider>().bounds;

            Vector3 topLeft = new (bounds.min.x, bounds.min.y, bounds.max.z);
            Vector3 topRight = new (bounds.max.x, bounds.min.y, bounds.max.z);
            Vector3 bottomLeft = new (bounds.min.x, bounds.min.y, bounds.min.z);
            Vector3 bottomRight = new (bounds.max.x, bounds.min.y, bounds.min.z);

            if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight)) break;
        }

        Instantiate(enemyPrefab, currentPos, spawnRot, enemiesDocument.transform);

        bool OnIsland(Vector3 position) => Physics.Raycast(position, Vector3.down, 1f, LayerMask.GetMask("Island"));
    }
somber nacelle
#

that doesn't change the fact that if your if statement is never true the loop will never end meaning no other code will run. so if that if statement is not true the first loop how could it ever be true on following loops?

gray mural
#

cause

#

i mean

gray mural
somber nacelle
#

then use the one that works if you are so sure it isn't an infinite loop

gray mural
#

nice

knotty sun
gray mural
#

oh

somber nacelle
#

you might also want to consider visualizing your physics raycasts so you can see where they actually are instead of making assumptions ๐Ÿ˜‰

gray mural
#

haha, yeah

knotty sun
grizzled bronze
#

real noob here

#

can anyone help me with something

gray mural
#

idk how is better to visualize raycasts

#

i mean

#

i am not in update void

knotty sun
grizzled bronze
somber nacelle
gray mural
#

I know Debug.DrawLine()

#

but I am not in update

#

how to I fix line?

grizzled bronze
#

I'm trying to follow a tutorial and im not sure where ive gone wrong for this last part to come up as an error

gray mural
#

use FindGameObjectWithTag

#

you are trying to find GameObject**s**

grizzled bronze
#

ohhhhhhhhh

#

thank you

gray mural
#

you need to find just one

grizzled bronze
#

I completely missed that

gray mural
#

or make it GameObject.FIndGameObjectsWithTag("LogicManager")[index]
(I hope it is array)

#

but you'd better not

grizzled bronze
#

been skipping back and rewatching this video for the past 30 mins trying to figure that out

#

thank you

gray mural
#

you'd better read error massages

#

in yr visual studio

knotty sun
grizzled bronze
gray mural
#

first find GameObject

#

then GetComponent

knotty sun
#

just in case you messed something else up

gray mural
#

does Debug.DrawRay work in non-update function?

somber nacelle
#

yes, why wouldn't it?

gray mural
#

cause it does not work in my case

#
if (OnIsland(topLeft) && OnIsland(topRight) && OnIsland(bottomLeft) && OnIsland(bottomRight))
            {
                Debug.DrawRay(currentPos, Vector3.down * 2f, Color.green);
                break;
            }
            else
            {
                Debug.DrawRay(currentPos, Vector3.down * 2f, Color.red);
            }
somber nacelle
#

well keep in mind if you still have an infinite loop how do you expect the frame to progress to actually draw the rays?

gray mural
#

i don't have

#

i have changed it

#

everything works perfect

#

expect those rays

somber nacelle
#

and how often are you calling the DrawRays? because you haven't set a duration which means it only lasts for the frame you call it on

gray mural
#

oh

#

how to I set direction to infinite?

#

not float.MaxValue i guess

somber nacelle
#

i mean infinite might be a bit much, but you can provide a decent number to the duration parameter to keep it up for a bit

gray mural
#

ok

#

i gonna try

final lotus
#

How do I scale UI properly across all/the majority of mobile devices

#

Cuz it seems like a lot of phone/tablet screen resolutions are very very different

#

should I just aim for a few mobile devices when creating an app instead of all of them

simple egret
#

Canvases have options to scale them with the screen size. Then it's a matter of anchoring your UI objects correctly so they're always in the right place whatever the screen size is

heady iris
#

you can use the CanvasScaler in "Scale With Screen Size" mode.

#

and then, yes, it's all about anchoring and positioning the pieces correctly

hard estuary
# final lotus How do I scale UI properly across all/the majority of mobile devices

Learn all about the Canvas Scaler! The Canvas Scaler comes by default whenever you make a Canvas in Unity, but many of us don't fully understand how it works or what it does. When making a game, ensuring your UI scales reasonably across multiple different aspect ratios and screen resolutions is critical.

In this video we'll dive deep into each...

โ–ถ Play video
final lotus
#

Yeah that's what I've been using

#

Ard, I'll just anchor the UI better, thanks guys

heady iris
#

Taking some time to learn how the different anchor modes work is very worthwhile

versed marsh
#

Hey, I have a question regarding combining multiple rotations, so if anyone has knowledge in the area, I would really appreciate some help.
I am making a 3D game that has the player walk around spherical planets. This is the player rotation code (in the Update method) that smoothly rotates the player based on my input vector:

if (input.magnitude >= inputThreshold)
        {
            float targetAngle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg;
            rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f,             targetAngle, 0f), rotationSpeed * Time.deltaTime));
        }

And this is the code for the player movement, which is in FixedUpdate:

if (input.magnitude >= inputThreshold)
        {
            rb.velocity = transform.forward * speed * Time.deltaTime;
        }

And this is my poor attempt to align the player to the ground using a raycast's normal (which is inside FixedUpdate):

RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit))
  {
    transform.up = hit.normal;
  }

Understanding and utilizing Quaternions is my weakest area in game dev, so all of my attempts of using things like Quaternion.FromToRotation and Quaternion.Lerp have led to very broken results. If anyone has a solution or could even point me in the right direction of how I could achieve this surface alignment system, I would be very grateful :)

#

sorry, long question ;_;

heady iris
#

Setting transform.up should do the trick.

#

If you do want to compose Quaternions, you can multiply them together. This gives you the result of applying both rotations.

#

However, rather than raycasting to the ground, I would rather just calculate the vector from the planet's center to myself.

#

otherwise, gravity will point all over the place as you walk up a slope

#

also, Vector3.down will shoot a vector in the -Y direction. I'm not sure if that's what you want.

steady moat
# versed marsh Hey, I have a question regarding combining multiple rotations, so if anyone has ...

Not sure what the following code is trying to do.

if (input.magnitude >= inputThreshold)
        {
            float targetAngle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg;
            rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f,             targetAngle, 0f), rotationSpeed * Time.deltaTime));
        }

Also, raycasting down will never give you a correct up. This is what you are trying to define. ๐Ÿ˜›

heady iris
#

if you are standing on the "bottom" of a planet, it will shoot a ray into space

steady moat
#

Like @heady iris said, you should use the closest planet to define the down. You could alternatively, use a whole bunch of calculation to add the gravity and figure out the highest gravity.

versed marsh
versed marsh
#

alright so I have this now in a seperate script:

[SerializeField] private Transform planetCenter;

    void LateUpdate()
    {
        Vector3 playerToCenter = planetCenter.position - transform.position;
        Vector3 newUp = -playerToCenter.normalized;

        transform.up = newUp;
    }

this does align the player with the planet's center, but since its directly modifying transform.up it just ignores the input-based rotation code I had before, and I'm not sure how to get around that

bitter basalt
#

Hello, I have a question, why does the "itemsInfo" list not appear in the editor if it is public?

bitter basalt
#

I see, thank you very much!

heady iris
#

yep yep -- you have to explicitly tell C# that this type can be safely turned into data (and retrieved from data)

austere basin
#

I am building my project via BuildScript on a Github runner.
I would like to build for Pico and Quest.

Unfortunately I can't get both features (Pico Support, Quest Support) to work at the same time and neither can I get the controller profiles.

Can I change the OpenXRPackageSettings.asset via script?

sonic zinc
#

if I want to use a canvas Ill do something like Public Canvas canvolini, but I want to grab a specific element on the canvas. What variable do I use for that. I want to get an image\

inner yarrow
#

There are certain scripts that allow you to give them a specific object's method that they will call if a certain condition is met. How would I go about making a custom script take in a method?

#

Here is an example of what I'm trying on the XR Grab Interactable component.

somber nacelle
ancient sail
#

hey everyone, does if im using IEnumerator as timer does it mean that it depends on frame rate

#

i use it to set values but main action goes on in fixed update

heady iris
#

do you mean you're calling StartCoroutine and passing the result of calling your function to it?

somber nacelle
heady iris
#

StartCoroutine(MyTimer()) or w/e

ancient sail
heady iris
#

coroutines get updated every Update

#

unless you yield a WaitForSeconds or something

ancient sail
ancient sail
somber nacelle
heady iris
#

if you yield a WaitForSeconds, then the coroutine will be resumed once that much time (scaled by timeScale) has passed

ancient sail
#

Okay, i was just a bit worried that it will mess up how my physics run, thanks guys

inner yarrow
sly gate
#

so, i got a small tower defense game goin on where you can freely place walls to block enemies, the walls work by having the component navmeshobstacle with the carve option ON, but now i want to add "flying" enemies which are supposed to just ignore and go over walls like theyre not even there. How can i achieve this with the walls blocking the navmesh?

latent latch
#

Layer masks?

heady iris
#

yeah, you want to add a new kind of area

sly gate
latent latch
#

Oh, you're not treating the walls as obstacles but carving a zone out

heady iris
#

if you use the new AI Navigation package, you get Nav Mesh Modifiers, which I'm pretty sure can target just one kind of area

#

o wait

heady iris
#

is this a third-party thing? I don't recognize NavMeshSurface2D

somber nacelle
heady iris
#

yeah, but I didn't think it had a separate surface type for 2D

sly gate
#

so should i just change how the walls work?

heady iris
#

can you show me this nav mesh surface?

heady iris
#

...what is this?

somber nacelle
#

oh wait, is that from NavMeshPlus?

heady iris
#

yeah, this is third-party

potent sleet
#

the github one

heady iris
#

lmao, i like the readme image

#

get that pepper

sly gate
#

i honestly did that so long ago i dont evenremember

heady iris
#

i have no idea about how this thing works

potent sleet
#

i just use the 3D navmesh with sprites lmfao

heady iris
#

but yeah, if you switch to the new AI Navigation package, you can get Nav Mesh Modifier Volumes

#

which can target specific kinds of areas

#

so, you'd have a Flyer layer that isn't affected

sly gate
#

time to start from the beginning!!!!

#

awesome

heady iris
#

well, it shouldn't be that bad :p

sly gate
heady iris
#

what version of unity are you using?

sly gate
#

2020.3

heady iris
#

AI Navigation only left experimental in 2022, iirc, but it is available back to 2019

sly gate
#

i dont think i see it in the package manager though

potent sleet
#

add package by name

#

com.unity.ai.navigation

heady iris
#

guess what was only made possible in unity 2021

#

back in 2020, you have to manually edit the package manifest

#

extremely goofy

sly gate
heady iris
#

it's not hard by any means, but just goofy

#

although

#

since you do have this NavMeshSurface2D

potent sleet
heady iris
#

i wonder if you could just put down two of them

#

but the nav mesh obstacle would hit both...

potent sleet
#

is the game top down or sum?

sly gate
#

this is straight up not worth my time honestly

heady iris
#

actually, I am curious

#

is there a component named "nav mesh modifier" ?

#

if so, you're good

heady iris
#

cool, there you go

#

that's what you'd be getting from the new package

#

I guess they've been backporting the features to this NavMeshPlus thingy

#

the modifier volume would probably be the easiest to use

#

you give it a volume and then tell it which areas to affect

sly gate
#

i remember trying to use it and having trouble with it, i dont remember exactly why though

heady iris
#

oh wait, that might require you to re-bake the mesh

sly gate
#

guess its worth a shot

sly gate
#

like. the wall's mesh?

heady iris
#

the navmesh

sly gate
#

doesnt sound to complicated

sly gate
heady iris
#

it's not bad, yeah

sly gate
#

ok... ill try switching out the obstacle component for the modifier and see if the wall still actually works for ground enemies

#

wait, the navmeshmodifiervolume is only for 3d right?

heady iris
#

you'd need to read the docs for NavMeshPlus to be sure; I'd expect it to work

sly gate
#

ill just use the normal navmeshmodifier for now

heady iris
#

oh, "volume" just means you give it an explicit region that it works in

#

i think the regular modifier is based off of the thing you attach it to

sly gate
#

@heady iris you still there?

#

tried it with the volume too that also didnt work

#

@heady iris ??

shell scarab
#
transform.localRotation = Quaternion.RotateTowards(Quaternion.LookRotation((follow.position + follow.forward * 2.5f - transform.position).normalized, Vector3.up) * Quaternion.Euler(0, 0, follow.localEulerAngles.z), rotateSpeed * Time.smoothDeltaTime);

Why when I add Quaternion.Euler(0, 0, follow.localEulerAngles.z) does the Z axis start flipping by 180 like it has gimbal lock or something, even if the local euler angles are 0? if it's Quaternion.Euler(0, 0, 0) shouldn't that equal Quaternion.identity, which multiplied by anything would just result in the same value?

heady iris
sly gate
heady iris
leaden ice
#

best to use your own float variable

heady iris
#

ah, yes

#

that would be exactly the problem

#

what do you want to do?

shell scarab
#

follow the z rotation of the object

shell scarab
heady iris
#

so matching its roll, basically

leaden ice
leaden ice
shell scarab
#

I've been bamboozled

#

thank you

#

I'll try tracking the z rot myself then.

heady iris
#

yeah, you see global stuff in the inspector

leaden ice
#

Nah it's local

#

My comment is more that euler angles are not unique and the inspector doesn't necessarily show the same set of euler angles as .localEulerAngles

heady iris
#

oh, right, duh

#

brain fart

#

they're all local.

shell scarab
#

@leaden ice so uh, I'm a bit confused again. I have this to track the z rotation:

public float zRot
{
  get => m_zRot;
  set
  {
    m_zRot = value;

    while (m_zRot > 360)
      m_zRot -= 360;
    while (m_zRot < 0)
      m_zRot += 360;
  }
}
private float m_zRot;
```It's only ever set through zRot.

However now it constantly spins as soon as I rotate the z axis, however before just reading the transform z axis it would not do that.
shell scarab
#

Sorry, I also changed the rotation code because the camera could not rotate fast enough to match the Z axis, it's actually fine if the z axis rotation is instant. This is the code that I'm updating the rotation on:

void LateUpdate() {
transform.localRotation = Quaternion.Euler(0, 0, follow.zRot) *
Quaternion.RotateTowards(transform.localRotation,
Quaternion.LookRotation((follow.transform.position + follow.transform.forward * 2.5f - transform.position).normalized, Vector3.up),
rotateSpeed * Time.smoothDeltaTime);
}
#

shouldn't this rotate the camera to be the z rotation, then apply the second RotateTowards rotation?

#

and doesn't Quaternion.LookRotation return Quaternion.identity if the from rotation is the same as the to rotation? so shouldn't it essentially be quaternion.euler * quaternion.identity? it doesn't, and it doesn't make sense that it would, but my question still stands. Shouldn't this set the z rotation then apply the other rotation?

#

and even if it didn't shouldn't it still be fine and not constantly spin it?

#

also, this is how I'm setting zRot:

private void WSADQE_performed(InputAction.CallbackContext context)
{
  m_preOrient = context.ReadValue<Vector3>() * rotationSpeed;
  m_preOrient.x *= pitchModifier;
  m_preOrient.y *= yawModifier;
  orient = Quaternion.Euler(m_preOrient);
}

private void WSADQE_canceled(InputAction.CallbackContext context)
{
  orient = Quaternion.identity;
  m_preOrient = Vector3.zero;
}

private void Update()
{
  transform.rotation *= orient;
  zRot += m_preOrient.z;

  transform.position = shipRB.transform.position;
}
lucid crow
#

so i have a public int score in a script attached to a game object in game scene which updates TMPro Ui on game screen so you can see a score. i want to use the value of score after the ball falls and resets you back to menu save it and list it as highscore in mainmenu. i have a json script and a playerdata script. I'm new to coding of course lol but if you want scripts let me know

#

main issue is how can i get the public value of score right before reset and save it. i cant seem to access score from other scripts

#

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

lucid crow
#

this is movement and score tracker

#

reset script

#

Json saving script

#

PlayerData script

#

idk if this needs to be in code advanced or not lol

#

think i need to seperate the score tracker from movement code first of all right?

#

i also thought this project was really good for me lol because it was just a paddle movment ball drops evertime it hits plus 1 point then if it falls go to menu and show highest score

heady iris
#

in what way can't you access the score from other scripts?

lucid crow
#

well if i try to use score as a value its not found

heady iris
#

what do you mean?

#

like, you get an error?

#

show me what you tried to do.

lucid crow
#

public void SetHighScore()
{
GetComponent<TextMeshProUGUI>(scoreText);
highscoreText.text = "HighScore: " + highscoreText.ToString();
}

heady iris
#

you are not accessing the score here

#

you are getting a text component and then setting its contents

#

also, this would just set the highscore to be the result of turning the highscore text object into a string

#

that does not make sense

quartz folio
#

there isn't even a GetComponent overload that looks like that (unless it's some undocumented nonsense)

heady iris
#

also yes

#

I'm kind of drunk right now so I completely glossed over that, lol

#

you invoke GetComponent on something

quartz folio
#

No, the generic overload returns a value and doesn't take one.
It's being implicitly invoked on this

heady iris
#

there is a one-argument form of GetComponent, but that's so you can pass it a Type

#

it's non-generic

#

ye

lucid crow
#

ok one sec

#

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

lucid crow
#

this is how im tracking and getting the score and then setting score added the last part of the code after i asked this question ๐Ÿ˜› then here is the other restart code

heady iris
#

yes, and that code is very ill-formed

lucid crow
#

yea im very new to coding...

#

first game i want to do a restart menu game score and a way of saving highscore and showing on mainmenu

#

thats it so its like all the basics

#

i was thinking i need a score manager

#

have a resart script and movment script to seperate it all

heady iris
#

that's a good idea, ye

quartz folio
heady iris
#

separation of concerns

#

one guy deals with movement

#

one guy deals with score

quartz folio
#

If you're not getting errors underlined in your IDE, you need to configure it !ide

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

lucid crow
#

yea ik it dont ๐Ÿ˜›

#

im getting red lined

#

i had something earlier and was just trying stuff while looking stuff up

shell scarab
#

ok I've narrowed my problem down.

All this code is in the LateUpdate() method.

Why does this spin infinitely on the z axis:

transform.localRotation =
Quaternion.RotateTowards(transform.localRotation,
Quaternion.AngleAxis(follow.zRot, transform.forward) * Quaternion.LookRotation((follow.transform.position + follow.transform.forward * 2.5f - transform.position).normalized, transform.up),
rotateSpeed * Time.smoothDeltaTime);

as well as this:

transform.localRotation = Quaternion.AngleAxis(follow.zRot, transform.forward) *
Quaternion.LookRotation((follow.transform.position + follow.transform.forward * 2.5f - transform.position).normalized, transform.up);

but this does not:

transform.localRotation = Quaternion.AngleAxis(follow.zRot, transform.forward);

Shouldn't the first two examples essentially do what the last example does, then apply the look rotation after the z has been rotated? (It also spins when I multiply the look rotation by the angle axis)

lucid crow
quartz folio
shell scarab
lucid crow
#

i also have another issue i create newscript name it and try to add it to emptygameobject and i get Cant add script component 'ScoreManager' becuase the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.

true palm
#

hey i have this code:https://hatebin.com/ebgrusosnb but when the player respawns on line 283 it gives me an error saying object reference not set to an instance of an object

lucid crow
#

the class name and the file name match

#

so idk

quartz folio
quartz folio
shell scarab
#

you mean like apply several rotations sequentially?

quartz folio
#

I mean have a nested transform, one that controls the Z axis, and one that does whatever else you want

shell scarab
#

I'm not sure if that would work. I'm controlling the camera rotation, so I need to control the z axis along with the x and y. The x and y by themselves work great actually, it's just when I try to control the z as well as x and y.

lucid crow
#

no // did the job but just fixed it somehow? just renamed the class and the file name to SManager and it fixed it even tho they was the same to begin with becuase i just created the script...

true palm
potent sleet
true palm
potent sleet
#

you just posted it

true palm
#

i reposted it

true palm
potent sleet
wise escarp
#

Hi!
I've been trying to make my code as modular as possible, and I've realized I may be able to take it further.

I, for instance, want to create a few "condition scripts" (On Collision, After Time, etc.) and several "function scripts" (SetActive, Do This, Do That, etc.) and be able to attach these two types of scripts any which way I please.

So for example, once the condition is met on the "After Time" script, it would execute any of the "Do This" scripts I've attached to it.

Problem is, I can't just attach any script I please -- I can only reference specific named scripts. Google hasn't yielded any results for how to go about this, if it should even be feasible or a good idea.
Is this feasible/a good idea, and if so, where/how can I begin to learn this? Thanks

shell scarab
#

you could use delegates

wise escarp
#

Thank you very much, this sounds like exactly what I'm looking for :)

shell scarab
clear moss
#

is there any way to create a dynamic script to find a possible army formation with a number of soldiers and a position to make the formation around, and return a list of the vectors for the soldiers?

clear moss
#

how would I do this. I tried using a for loop to create it, but it doesn't avoid obstacles

cold parrot
#

Well, you could check locations for collisions in your for loop and exclude those

clear moss
#

wouldn't that leave some soldiers without a spot to go to?

cold parrot
#

You could maybe continue looping until all have found a spot

clear moss
#

ok

#

if the number couldn't be perfectly squared, how would I find the best possible fit?

cold parrot
clear moss
#

the most box like, and evenly spread out, so that its as square as possible

cold parrot
#

You can only find the best solution by trying all solutions, but you can get to a good enough solution by limiting the search range or simply appending all soldiers without a spot to the end of that box formation, turning it into a slightly rectangular shape

clear moss
#

ok

#

thanks

solar jolt
#

anyone got a solution for ignoring folders on build?

cold parrot
#

If you want to exclude a folder from the asset database, suffix it with a ~

solar jolt
#

my build sizes are still hitting approx 100mb is it not possible to shrink it more? (simple project, 1 scene, have some packages I have pulled in from the asset store but not referencing any of those scenes in build scenes).

steady moat
solar jolt
slim flower
#

Does anyone here know stuff abt Mirror Networking?

heady iris
#

Donโ€™t ask to ask. Just ask.

slim flower
#

my bad

steady moat
desert mist
#

I am having an issue trying to calculate the pitch angle of a calculated Vector3 direction. I know I am doing something wrong and I am absolutely too brain-fried to see what the issue is. Attached is a crude diagram that shows what I am trying to do, where CT and LO are both Vector3s. I need the red pitch angle readings returned as a float.

First, I subtract the two vectors to get a direction that points from CT to LO:

Vector3 calculatedDirection = LO.position - CT.position;

From this point, I have attempted a lot of things including Quaternion.LookRotation and FromToRotation, but the end result is incorrect. With the code I have tried, the position of CT on the XZ plane alters the reading of the pitch angle when the angle is supposed to equal zero.

lethal rivet
#

How can get the top and left screen space points of the screen space bounding box on a mesh in the scene, so I can position a UI there like in this example, red representing the screen bounding box.

maiden fractal
lethal rivet
#

Yeah... that's why I came here hah

#

I thought that maybe Camera has a built-in function that does something similar to that

desert mist
# buoyant crane https://docs.unity3d.com/ScriptReference/Vector2.SignedAngle.html CT is your `fr...

I need it to be compatible with Vector3, but only account for angle change along a YZ plane relative to CT. Assuming that both CT and LO can move positions, the only angle I care about is the pitch difference. If CT's Y position is below LO's Y position, the angle should be a positive angle value, and any change in relation to the positions of either should not effect the angle so long as the Y positions of both remain the same.

lethal rivet
maiden fractal
lethal rivet
#

Alright, thank you!

buoyant crane
buoyant crane
#

since z is technically your x axis

desert mist
#

I tried using Vector3.SignedAngle, but it did not have the correct output.

buoyant crane
#

Vector3 signed angle needs the correct axis that you are rotating along, but if itโ€™s only going to be on a single axis, itโ€™s easier imo to just use vector2 signed angle

desert mist
#

Unfortunately, that also gives output that does not achieve what I need. But thanks for trying, I'll just try again later when I am not so tired, maybe I will figure it out then.

buoyant crane
granite nimbus
#

is it possible to make some calculations run on gpu?

lapis bramble
#

hey guys ๐Ÿ‘‹

small hemlock
#

so any help with nullreference errors in only build mode?
the issue seems to be that my scripts cannot reference anything outside its own gameobject

granite reef
#

Hi, can anyone help me figure out what is wrong with my code or give me some good resources? I'm trying to make a yo-yo game but the physics have been really hard.. Currently i'm working on a rope that can expand and contract and keeps the yo-yo tether to a finger. The rope pretty much works sometimes, but it spazzes out like crazy pretty often and doesnt really obey gravity.. also the yoyo starts spinning very quickly

https://gdl.space/raw/salaxapebu

small hemlock
#

any references to components in its gameobject doesnt give erros

cosmic rain
#

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

cosmic rain
small hemlock
#

the problem is that i have about 40 scripts and i dont think its gonna be too helpful to post all of them

#

i do think can bring the error logs and the parts applicable though

cosmic rain
#

Start from posting the error. Then the code that is relevant to it.

small hemlock
#

NullReferenceException: Object reference not set to an instance of an object
at generalmovementscript.Start () [0x0014e] in C:\Users\Admin\New Unity Project (2)\Assets\scripts\generalmovementscript.cs:100

(Filename: C:/Users/Admin/New Unity Project (2)/Assets/scripts/generalmovementscript.cs Line: 100)

cosmic rain
small hemlock
#

this is the code applicable

granite reef
#

@cosmic rain it doesn't need to be accurate, but i would like for it to be somewhat convincing

basically i have no idea, as long as the yoyo works pretty much correctly i think it will be fine

small hemlock
#

i could post the entire thing but i am doubting that it'll actually help

cosmic rain
# small hemlock

Logically thinking, enemyyList object doesn't have a child named hitbox.

small hemlock
#

oh that was just bad naming practice sorry

#

enemylist isnt actually a list its just one

#

i was trying to consider multiple enemies at once but then realized that i didnt need to

cosmic rain
#

Yeah, I figured that much.

#

It doesn't change what I said.

granite reef
small hemlock
#

which the code is referencing

quartz folio
#

that's nice, does the enemyyList object have a direct child named hitbox?

small hemlock
#

yes

cosmic rain
#

Not according to the error.

#

Are you instantiating these hitboxes at runtime?

small hemlock
#

thats the strange part im saying

quartz folio
#

I am pressing ๐Ÿ‡ฝ to doubt

cosmic rain
small hemlock
#

am i supposed to add a line that instantiates those and if so what is it

quartz folio
#

we have no idea what you're doing, or what objects you're looking at

small hemlock
#

this is the one for the supposed enemy

cosmic rain
small hemlock
#

like im dont know what you actually mean by instantiating it

cosmic rain
quartz folio
small hemlock
#

there is just one

small hemlock
#

by instantiating i assume you mean that i create those objects

formal niche
#

there is no

granite reef
formal niche
#

"hitbox" under the transform component

#

so you cant do .name

small hemlock
#

there is supposed to be a hitbox though

#

and there is one so this error doesnt happen in the editor

formal niche
#

hm sry i rushed a bit

#

let me look a bit more

small hemlock
#

i think i should test something rq because i found something that seems weird to me

#

because it seems to be able to recognize another gameobject it seems?

formal niche
#

wait check for null for the different components

cosmic rain
small hemlock
#

oh i think that it might have to do with the execution order of child objects compared to regular scripts

small hemlock
formal niche
small hemlock
#

the object itself returns null so

#

its kinda obvious what would happen if i wanted to return a component from it

#

which is why i added that line

#

the components were not getting recognized

#

so i added a line to check if it was the object itself or just the components

granite reef
formal niche
cosmic rain
formal niche
small hemlock
formal niche
#

for another child

small hemlock
#

for another child?

cosmic rain
#

loop and log all the children of the object. That might give some clues.

formal niche
#

yeah also it is generally suggested to not use Find

small hemlock
#

i can do that by getchild right?

formal niche
#

yeah

#

as well

#

but im assuming you are using Find so order doesnt get messed up

small hemlock
#

yep thats why im using it

formal niche
#

can you print out

#

transform.GetChildren()

#

sry wait

#

er

cosmic rain
#
foreach(Transform child in enemyyList.transform)
  Debug.Log(child)
formal niche
#

yeah

#

thank you

#

sry

small hemlock
#

hold on

granite reef
cosmic rain
#

That being said, moving a transform directly, could be messing with physics.

formal niche
#

when it reaches the end of the line

#

so it just builds up velocity

granite reef
formal niche
#

and when you decrease the transform

#

all that velocity kind of just yeets the thing

granite reef
granite reef
small hemlock
#

why the hell is my editor taking 5 minutes to reload script assemblies

formal niche
#

?

formal niche
granite reef
formal niche
#

i would suggest rather than setting the rigidbody to the one of the points

#

to simply use an addForce or smthing to simulate the tension

granite reef
#

that does sound like a better approach

#

what is addforce?

formal niche
#

rb.AddForce

cosmic rain
# granite reef here is the code on the rope object https://gdl.space/raw/fobugatexi

That's the code from before.
I don't see anything related to velocities/force in here.
The only things affecting movement/position I see are these lines:

startPoint.position = fragments[0].transform.position;
endPoint.position = fragments[fragmentCount - 1].transform.position;

fragments[i].GetComponent<Rigidbody>().position = Vector3.zero;

And it would make sense that they break something, since you're setting the position directly.

granite reef
#

yeah... that was the only way i could get the string to connect to the yoyo and the blob

#
            endPoint.position = fragments[fragmentCount - 1].transform.position;

            var vy = Input.GetAxisRaw("Vertical") * 20f * Time.deltaTime;
            activeFragmentCount = Mathf.Clamp(activeFragmentCount + vy, 0, fragmentCount);

            for (var i = 0; i < fragmentCount; i++)```
here, var vy is input, yes?
formal niche
#

ig?

cosmic rain
#

I recommend learning first how real world yoyo physics work, what forces are acting on each object and on the rope itself at each point in time. Then research the limitations of unity physics simulation and consider how to implement it.

#

Honestly, it's not something I'd do as a beginner

granite reef
#

sorry this was probably not a good first project idea.. but i appreciate the help

formal niche
#

yep, just imagin right

#

if a yoyo just teleports

#

imagine its gonna keep going fasteruntil it reaches terminal velocity

#

mostly the same in unity

#

except id know if theres terminal velocity

granite reef
#

it sounds really hard to implement lol

#

i didnt think id really have to think about real forces

cosmic rain
#

Unity physics mostly follows the same rules

#

If you don't wanna think about it, might as well avoid using physics at all

formal niche
#

so either you use physics for basically everything or no physics at all

granite reef
cosmic rain
#

Having a yoyo act close to real life analogue would require physics calculations, regardless of whether you delegate it to unity physics or do yourself. But both imply that you understand the physics behind how yoyo works.

formal niche
#

btw something i would suggewt you to change is to make the holding a point on the line

#

change which point it is

#

so it doesnt infinitely stretch it

#

but that definitely has some usages as well

granite reef
#

the holding point is on the line rn, but im not rly sure what you mean

formal niche
#

how are you holding the line with your mouse

#

cant see a script for it

granite reef
#

ill post 1 sec, but it would be cool if it didnt infinitely stretch

small hemlock
#

no errors no logs no nothing

formal niche
#

um that means that there are no children for that transform

#

wait

granite reef
#

also, if you 'contract' the rope, and the point that you are holding onto gets deleted, you let go of it

formal niche
# formal niche wait

try something lik
for(int i=0;i<PlayerList.transform.childcount;i++){
Debug.Log(PlayerList.transform.getChild(i).name);
}

#

the rope is made out of many different rope objects right

granite reef
#

yea

#

there is spring joints between all of them

formal niche
formal niche
#

(note this will be less performant)

#

to, first of all, limit the distance(through rb2D.addForce back to a connected point probably with force directly related to distance or something like that) and to check which point is the closest to the mouse when dragging rather than have a point be permantently held

small hemlock
#

they were added at the start

granite reef
small hemlock
#

like in the scene itself

white moon
#

i cant fix this pls help

formal niche
formal niche
white moon
#

omnipath

formal niche
cosmic rain
tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

granite reef
#

@formal niche yea.. its not too bad but im gonna have to read the docs a lot to figure out how to get them connected with force

granite reef
formal niche
#

um if you have a rigidbody2D

#

you can have a meshrenderer and everyh\thing

#

3D

granite reef
#

its a 3d rigidbody rn

formal niche
#

then you cant use the 2D version of the scripts

#

although idk why you would

#

need to

#

most of them are the same

#

or similar

granite reef
#

ah alright

#

thanks for all the help

formal niche
#

np

small hemlock
#

wait how should i check if it is added to the same one

formal niche
#

just look at the object

small hemlock
#

im not really fond with the debugger yet

formal niche
#

after inspector in runtime

small hemlock
#

in the editor?

#

oh uh

formal niche
#

yeah ig

small hemlock
#

i havent used the inspector in runtime yet where can i open that

formal niche
#

um

#

scrnshot

#

your unity

small hemlock
#

oh wait

#

you mean

#

the one in the right?

formal niche
#

YEAH

#

oops

#

caps

#

see if the component is added to the right gameobject

small hemlock
#

does it accout for what happens in build too?

white moon
#

pls help with my issue i intsaleed .net 7 also but its not working

formal niche
small hemlock
#

its not changing at all when i run a game build for some reason

formal niche
#

so when the script runs

#

the component doesnt get added

#

or wht

formal niche
white moon
#

nope i a need autocomplte

small hemlock
#

the component does get added when i play it in the editor

formal niche
#

oh

#

you mean the build

#

is different

small hemlock
#

yep

white moon
#

its not showing basic code also like transfor

formal niche
#

from the editor

small hemlock
#

this entire issue is only happening in the build

formal niche
#

are you building widnows

#

windows

#

or what

small hemlock
#

pcmaclinux standalone

formal niche
#

seems to maybe be a recurring issue idk