#archived-code-general

1 messages · Page 355 of 1

swift falcon
#

bruh like this eh?

hidden compass
#

bruh, try it and see eh?

rigid island
#

ide is suggesting about keycode sadok

swift falcon
#

Yup it works, but like, how do i disable it for y axis lol, if i look up, i go flying

rigid island
#

well thats because you're chaning the X rotation

#

probably

hidden compass
#

sooo.. ur forward axis points up

rigid island
#

only change the X rot on the camera

swift falcon
#

no

#

but i wanna look up

#

But i dont wanna move up and down like a bird

rigid island
#

then dont rotate the chracter up?

#

cinemachine has a built in TPV camera why dont you start with that?

#

all you do is rotate the target up/down on X of camera

swift falcon
#

Huh? I dont think ur getting, Look, that code adds force to direction where player is looking, now i want this to affect the X and Z axis, meaning that if i look at Z it moves towards Z, and If i change my X roation or view, it adds force to X, but if i change Y axis, i dont want it to move up or follow or react with that change of view in Y axis

rigid island
#

Rotating X is pitch

#

if ur pitching your character Up then you are flying up because of relative velocity in forward

#

typically you setup.
Camera = only rotates X (pitch using mouse Y)
Character = Rotates only on Y (using mouse X axis)

swift falcon
#

alr alr

rigid island
#

well ig in third person view you dont have to use mouse to rotate char

#

if you go forward using the camera's forward relative velocity thats ur issue, use character's instead

light pond
#

no i mean my movement script and do tween in start() works but in update doesnt

leaden ice
hidden compass
#

so no matter if i look up or down.. the player object will still be facing a direction thats parallel to the floor

swift falcon
#
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;


public class PlayerCoreConfig : MonoBehaviour
{

    public Transform Core;
    public Transform Player;

    public float speedMP = 0;

    Rigidbody rb = FindObjectOfType<PlayerMain>().rb;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Core.position = Player.position;
    
    
        if (Input.GetKey("d")){
            
            rb.AddRelativeForce(Vector3.right * 15 * speedMP);
    }
            if (Input.GetKey("a")){
            
            rb.AddForce(speedMP*-50*Time.deltaTime, 0,0);
    }
            if (Input.GetKey("w")){
            
            rb.AddForce(0,0,speedMP*50*Time.deltaTime);
    }
            if (Input.GetKey("s")){
            
            rb.AddForce(0,0,speedMP*-50*Time.deltaTime);
    }

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

public class PlayerMain : MonoBehaviour
{
    // Start is called before the first frame update
    public Rigidbody rb;
    public float speedMP = 0;
    public Transform player_position;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

    

    }
}
#

I know i made a mistake

#

i cant locate it

rigid island
swift falcon
#

mb dint know, btw, PlayerConfig is an empty Object

rigid island
#

Rigidbody rb = FindObjectOfType<PlayerMain>().rb;

#

why

#

just make a field in the inspector , put the script ont he same object. why do this

swift falcon
#

Uhh ok so look, the Rigid Body is a ball, so it will rotate like a ball, which means like

#

Uhh its gonna be ahrd to explain, i have to type a lot

#

just hang on

rigid island
#

there is so much wrong with this code

#

you NEVER add time.deltaTime to AddForce, also rigidbodies should be moved in FixedUpdate

#

are you just guessing this or

hidden compass
#
    {
        Core.position = Player.position;

        Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        Vector3 force = new Vector3(input.x, 0, input.y) * speedMP * 50;

        rb.AddRelativeForce(force);
    }```
#

jus saying

rigid island
hidden compass
#

oof

swift falcon
#

So Since its like a ball, when i directly add force to the ball, it will rotate, which means (with refrence to photos) it will turn from picture 1 to picture 2 and like this AXis will be randomized, which means the forward will sometimes be down, sometimes up, sometimes right and left, so for this, i need a core, that doesnt rotate when the ball rotatesfor which i use the playercore, which means it will add force in direction of pointing to playercore

hidden compass
light pond
rigid island
# hidden compass oof

AddForce will still wait for the Fixed physic step to apply the value so its already good to go

#

consistent

hidden compass
#

yea yea, ofc..

swift falcon
#

So read what i sadi

#

did u guys understand?

#

😭

hidden compass
#

yes, we understand

#

why not just lock its rotations?

#

u can still move it around.. w/o needing it to rotate..

swift falcon
swift falcon
#

it has a cool effect

hidden compass
#

u cant tell if its rotating or not

swift falcon
#

for now

hidden compass
#

ahh ok ok

swift falcon
#

so this is the only logical thing my racoon brain could ocme up wiht

hidden compass
#

interesting.. not gonna be a clear-cut solution for that

swift falcon
#

brah

#

There has to be something i can do

leaden ice
hidden compass
#

use the camera for the correct movement directions if u can @swift falcon

leaden ice
#

you cannot treat quaternion components like euler angles

#

they are not euler angles

light pond
#

so quaternion. what?

leaden ice
#

nothing

#

i don't know why you're doing that

#

0 goes there at the end

light pond
#

(0,180,0) ???

leaden ice
#

yes

hidden compass
#

@swift falcon
Vector3 projectedDirection = Vector3.ProjectOnPlane(Player.TransformDirection(moveDirection), Vector3.up).normalized;

swift falcon
#

shut up

hidden compass
#

no memes

swift falcon
#

mb

hidden compass
#

if u project the direction to a plane.. using the Vector3.up direction

swift falcon
#

but not only plain

hidden compass
#

it makes the direction perpendicular to the ground

swift falcon
#

i will add terrains

#

mountains

#

and stuff

hidden compass
#

it doesnt matter..

#

the plane is imaginary

#

it just level w/ the horizon since we use Vector3.up

#

ur forces would end up like this

swift falcon
#

alright

#

so how do i use it

light pond
swift falcon
#

brah

#

it doesnt even work

leaden ice
leaden ice
swift falcon
wide terrace
leaden ice
#

pay attention to your errors

#

they have words in them

simple egret
#

Double-click the error to navigate to it. They should be clearly visible (underlined red) in the code

leaden ice
#

you can read the words and get information

swift falcon
#

oh

#

brah

#

ok still

leaden ice
#

yep, looks like a simple problem you should fix

swift falcon
#

Brah

#

I have other things to worry about

#

😭

leaden ice
#

sounds like you're too busy to learn to code

swift falcon
#

mb

simple egret
#

The code Spawn posted is an example, it is not meant to be copy-pasted blindly, you should adapt it

swift falcon
#

alright

#

now what

#

Im gonna slep

#

drop ur stuff here now

light pond
# leaden ice solutions

problem is dotween is not allowiing anything to change rotation so basically its doing "transform.DORotate(new Vector3(0,0, ZRotateTo), 2, RotateMode.Fast)" so its not even flipping

#

is there a way to make public floats null?

wide terrace
# swift falcon now what

Now... projectedDirection is the player's forward direction projected onto the world x/z plane, such that it's not pointing up or down anymore.

I'm not sure what you were doing with that 🤷

leaden ice
#

why are you using DotTween if you don't want DOTWeen to control the rotation

#

You haven't even explained to anyone what you are trying to do

#

What is your goal?

light pond
#

here you can see what im trying to do

light pond
#

when i turn on dotween spin script

#

its a small rotation but it kinda makes the player look like he is flying

leaden ice
#

put your sprite on a child object

#

and do that little animation on that child object using Local Rotation

thin aurora
leaden ice
#

Leave the parent object to do the main player movement/rotation

light pond
#

ok ig i can try that

rigid island
light pond
thin aurora
#

They can be nullable.

#

Just change the type to a float? or Nullable<float>

#

I was just confused what the public has to do with it

knotty sun
#

I dont think nullable value types are serializable by Unity

rigid island
#

nope

leaden ice
#

they don't need a nullable float

#

that was an XY question

glad sentinel
#

Quick question, i added a parallax script to the BG objects in my scene, with each layer having a parent object for grouping, and I attached the script to the parent objects, but I get an error bc its trying to access a Sprite Renderer that isnt on the parent even tho it is on the Child Objects, why isnt it picking up the Renderers?

leaden ice
#

they were actually asking "How do I make DOTWeen not do anything"

leaden ice
#

either your code is assigning them or you assigned them in the inspector

#

and you did one of those things incorrectly

glad sentinel
leaden ice
#

that isn't helpful

#

you'd need to show your code

#

and/or how you assigned the renderer

#

and please don't take a photo of your screen

glad sentinel
#

public class Parallax : MonoBehaviour
{

private float _startingPos;
private float _lengthOfSprite;
public float parallaxAmount;
public Camera MainCamera;

// Start is called before the first frame update
void Start()
{
    _startingPos = transform.position.x;
    _lengthOfSprite = GetComponent<SpriteRenderer>().bounds.size.x;
}

// Update is called once per frame
void Update()
{
    Vector3 position = MainCamera.transform.position;
    float temp = position.x * (1 - parallaxAmount);
    float distance = position.x * parallaxAmount;

    Vector3 newPos = new Vector3(_startingPos + distance, transform.position.y, transform.position.z);
    transform.position = newPos;
}

}

#

here

thin aurora
tawny elkBOT
glad sentinel
#

whoops

light pond
leaden ice
glad sentinel
#
public class Parallax : MonoBehaviour
{

private float _startingPos;
private float _lengthOfSprite;
public float parallaxAmount;
public Camera MainCamera;

    // Start is called before the first frame update
    void Start()
    {
        _startingPos = transform.position.x;
        _lengthOfSprite = GetComponent<SpriteRenderer>().bounds.size.x;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 position = MainCamera.transform.position;
        float temp = position.x * (1 - parallaxAmount);
        float distance = position.x * parallaxAmount;

        Vector3 newPos = new Vector3(_startingPos + distance, transform.position.y, transform.position.z);
        transform.position = newPos;
    }
}

#

better?

leaden ice
leaden ice
# glad sentinel

as per this image, there is clearly not a SpriteRenderer on the same object

#

so it fails

#

case closed.

light pond
#

is it because the Xrotateto and the yrotateto arent assigned and are 0

leaden ice
#

i have no idea what you've done in the meantime

#

so i can't answer that

leaden ice
light pond
leaden ice
#

the y axis of the child should never change

light pond
#

well its changing

leaden ice
#

again, you should now be modifying local rotation

#

sounds like you're not doing that

#

you're probably still modifying its world space rotation

leaden ice
light pond
#

wait soo movement script of player should be local instead right

leaden ice
#

no

#

movement script is no longer relevant

#

we're talking about the child wiggle now, correct?

#

your movement script was fine

light pond
#

where do i adjust local rotation?

leaden ice
#

wherever you want

#

i don't understand the question

#

In a script, presumably

light pond
#

the tweening script?

leaden ice
#

whatevewr script you want to use to do the local rotation thing

light pond
leaden ice
#

depends

#

what is transform?

#

i.e. - which object is this script on?

light pond
#

yo it works

#

thank you so so so so so so much

#

i just did

#

DOLocalRotate

#

fixes everything

leaden ice
#

yeah, because that actually does local rotation

light pond
#

thanks

tender jolt
#

Is this the following code to get the pitch "pitch = Vector3.SignedAngle(new Vector3(0, dir.y, dir.z), forw, Vector3.right)?"

stable lintel
#

Can i open prefab editing window with code?

#

this one

stable lintel
#

AssetDatabase.OpenAsset(savedPrefab);

#

i kinda did it this way

#

not sure if it's not gonna cause bugs

#

thanks anyways

serene stag
stable lintel
#

i'm opening prefab editing window

#

with code

serene stag
#

Ok.

stable lintel
#

don't ask why i'm not sure myself if i need it

serene stag
#

I never did that too.

winged pier
#

hey, does anyone know if there's a way to use transform.forward with a Vector3? i'm moving my character with Rigidbody.AddForce(desiredForce), but im trying to implement moving in the direction the character is looking in.

#
public class PlayerMovement : MonoBehaviour
{
    // COMPONENTS
    Rigidbody rb; PlayerInput pi;

    // INPUT
    InputAction moveAction;

    // MOVEMENT
    Vector2 moveVector;
    float speed = 8f;
    Vector3 desiredForce; Vector3 desiredVelocity; Vector3 targetVel; Vector3 _currentVel;

    void Start()
    {
        // COMPONENTS
        rb = GetComponent<Rigidbody>(); pi = GetComponent<PlayerInput>();

        // INPUT
        moveAction = pi.actions.FindAction("Movement");
    }

    void FixedUpdate()
    {
        desiredForce = ((rb.mass * desiredVelocity) - (rb.mass * rb.velocity)) / Time.fixedDeltaTime;
        rb.AddForce(desiredForce);
    }

    void Update()
    {
        moveVector = moveAction.ReadValue<Vector2>();
        targetVel = new(moveVector.x * speed, 0f, moveVector.y * speed);
        desiredVelocity = Vector3.SmoothDamp(desiredVelocity, targetVel, ref _currentVel, 0.1f);
    }
}
#

i tried using addrelativeforce but whenever i moved while rotating, the player kinda flew away at astronomical speeds

cold parrot
winged pier
#

like if i applied an explosion impulse, if the player was moving wouldnt it just do nothing

cold parrot
#

yes, but you are also overriding the velocity through your force calculations

#

so you cannot use external forces, since you are not respecting them

winged pier
#

wait yeah

cold parrot
#

it seems to me you're approach tries to mostly eliminate the whole point of having force simulation

#

you'd typically just add a break / acceleration / steering force of magnitude X with X < mass * speed (and maybe scale that down the closer you get to your target velocity). You would not actually attempt to correct with a massive singular force that changes the velocity in one frame to a substantially different new one.

winged pier
cold parrot
#

that is position and rotation

winged pier
#

alr tysm 🙏 really helpful

swift falcon
#

does particle systems throw an event after playing and when all particles died? I want to make a Particle system pool

spring creek
swift falcon
#

yea Im currently doing it via coroutine and IsAlive

#

would have been nice if there's an exposed event tho, or an official PS pool by unity at least

rigid island
gleaming falcon
#

Hi! I'm making a 4 key rhythm game. However, i've been stuck on getting the game to recognize when you've hit a note in the correct amount of time. I've been trying to figure it out for a while and its something thats put me off wanting to work on it. Can someone help me wrap my head around a way i could implement this?

Here are some scripts that might be useful

The parser that parses the beatmap files (probably not important but just in case):
https://paste.ofcode.org/kn6TnL6CbJHXMfkwtDe8qQ

My current input method (messy and doesnt work lol):
https://paste.ofcode.org/8YBNbVFS6v4xsRQEHgPSRb

The script that actually spawns in the notes:
https://paste.ofcode.org/32BSkCknG4GxDs5fhqJJTGg

If anyone could help out with this it would be greatly appreciated as it is the main hurdle im stuck with right now

gloomy helm
#

how can i rotate and object around another object by a specific amount?

gloomy helm
#

yea i am in the docs right now

#

trying to figure it out

#

it is just rotating infinitely even when i put the angle to 1 the angle acts like the speed not how much i want it to rotate

somber nacelle
#

sounds like you are calling that method every frame instead of only when you want to rotate

gloomy helm
#

ok i solved it

nimble pier
#

Does anyone know how to get GetPixelBilinear to work?cs Debug.Log($"{heightmapTest.GetPixelBilinear(2000, 2000)}"); Debug.Log($"{heightmapTest.GetPixelBilinear(4000, 4000)}"); Debug.Log($"{heightmapTest.GetPixelBilinear(6000, 6000)}");I get the same output no matter where I sample from. I've tried turning compression off, but crunch compression is turned off either way...?

mossy snow
#

all 3 of those lines sample the same point. Did you look at the docs?

viscid mist
#

I put a Time.timescale into one of my UI codes would it be a better idea to place it inside of a game manager file and to reference the ui code into the game manager

golden wave
#

What's a good way to get the Player reference on each Monster when it spawns, so the monster can check if it's in range of the player to attack?

#

Is this where you use FindWithTag?

#

My game will eventually have multiple player characters, so I can't make it a singleton

#

Or do I add like a static game manager that has the reference to all the player characters that I can access from each monster?

somber nacelle
#

why not use a physics query like an overlapbox instead? then you don't need a direct reference to the player, you just check if any of the detected colliders is the player

golden wave
#

I'll look into that, first time I do something like this

golden wave
#

I might want to add ranged enemies too at some point

somber nacelle
#

whichever one is the shape you would like to check

#

there is no separate difficulty level for calling different methods that do similar things

golden wave
#

my first thought is collider cast?

somber nacelle
#

you do realize i literally gave a suggestion as to what would be an appropriate option, right? but again, it entirely depends on how/where you want to check and the behavior you are attempting to create

golden wave
#

ah overlap box, oopsie 🙂

#

but that wouldn't work for ranged attacks?

somber nacelle
#

but again, it entirely depends on how/where you want to check and the behavior you are attempting to create

golden wave
#

yeah 🙂 I think a simple ray cast is probably best then

#

it's comparable to a 2d platformer, but without jumping lol

#

and no objects/obstacles in the way either

somber nacelle
#

a raycast works if you already know what direction you want to check in. it does not if you are simply trying to determine if any player is within range in any direction.

golden wave
#

monsters just move left towards the player (this never changes, nothing blocks them)
and attack the player when they get in range (melee or ranged)

#

yeah so raycast is perfect in my case then

#

I always assumed raycasts where something expensive & difficult

somber nacelle
#

no, raycasts are incredibly cheap

golden wave
#

perfect 🙂

#

if you keep helping me like this I'll have to end up giving you a share of my profits lol

worn stirrup
#

Won’t be awake much longer but I just realized I can ask here… been trying to wrap my head around the idea of getting the distance of two objects and applying that distance to another object, scaled and rotated. The idea is to compare the position of each player against the camera that’s at the center of the level and use that to place their nametag on a realtime map elsewhere in the scene to align each player’s name tag on the map. It’s for a multiplayer game I’m doing.

lean sail
worn stirrup
#

camera is orthographic and the map itself is a square, but it seems like the scaling applies lesser in the Y direction than the X somehow and I don't really understand how that's possible

#

so more or less the question is if there's any glaring issue with the code I posted that could explain why my scaling seems wildly dysfunctional 😅

#

Any insight or suggestions would be appreciated!

#

also sort've confused as to why I had to go for 90 + 45 degrees on the rotation in order to even get it to align with a map that's just on a wall, but maybe I just don't get the math complexity

lean sail
#

honestly a lot of this looks like magic numbers

#

the 0.03 scalar, this seemingly random euler angle rotation, and subtracting -0.15f from the z on the vector

worn stirrup
#

😬 yeah I have no clue how to approach this. I have an inkling I should be using TransformPoints to correctly find and translate the differences in world space…

fair jackal
lean sail
#

ah sorry yes its setting

fair jackal
worn stirrup
lean sail
#

ok well getting rid of it just doesnt magically solve anything. im just pointing out that its really hard to suggest much because a lot of these numbers are magic and we dont know why you need them. Other than they just work because it was hardcoded in

golden wave
#
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.left, 10, layerMask);```
Why is this still hitting things not in my Characters layer?
worn stirrup
fair jackal
somber nacelle
fair jackal
#

Away from the camera?

worn stirrup
fair jackal
#

Ah ok

worn stirrup
#

The point of the Euler rotation is that the camera is a top down way out somewhere but I need to translate that relationship to be on a wall

lean sail
#

you would usually use some vector projection to translate a vector like this

worn stirrup
lean sail
#

its somewhat hard to type out what it means, diagrams from online will be a lot better

fair jackal
#

Is that projecting things onto a bigger/smaller surface using vectors

#

Like if you moved a flashlight away from a surface (the light cone gets bigger)

worn stirrup
#

That sounds like more what I wanted. The above code definitely tries to do that too but it’s a lots more rudimentary heh, thank you for a new direction for tomorrow!

#

Hopefully I remember to ask here sooner next time I get stuck

golden wave
#

Debug.DrawRay(transform.position, Vector2.left * 100, Color.red, 10, false);
can't get this to work either

grizzled ibex
#

You'll want to remove the bitwise NOT (~)

golden wave
#

yeah I fixed that 🙂

indigo tree
# fair jackal Like if you moved a flashlight away from a surface (the light cone gets bigger)

Wikipedia has some helpful formulas:
https://en.m.wikipedia.org/wiki/Cone

A cone is a three-dimensional geometric shape that tapers smoothly from a flat base (frequently, though not necessarily, circular) to a point called the apex or vertex.
A cone is formed by a set of line segments, half-lines, or lines connecting a common point, the apex, to all of the points on a base that is in a plane that does not contain the ...

somber nacelle
grizzled ibex
golden wave
#

ah you have to actually click the word gizmos wtf

#

that is extremely unclear

grizzled ibex
#

Yeah, it's a bit weird

indigo tree
fair jackal
#

I know burst is fast, but what’s the downside 🤔

golden wave
#

Debug.DrawRay(transform.position, Vector2.left * 100, Color.red);
Is transform.position supposed to be the bottom center of my object? Or did I set it up wrong?

indigo tree
fair jackal
#

Both i guess

somber nacelle
spring creek
fair jackal
#

Oh, interesting

indigo tree
# fair jackal Both i guess

The downside of Unity.Mathematics is that you have to write everything in camel case lol.

The downside of burst is it compiles things differently than how Unity normally does it.

fair jackal
#

I’ve never even heard of Unity.Mathematics, is it new?

spring creek
fair jackal
#

Ah ok, then maybe it’s because i’ve never looked into DOTS

spring creek
#

I'm sorry, I meant that it is linked to it. A lot of DOTS relies on it

cosmic rain
#

It's part of the stack

wide terrace
#

DOTS is composed from a number of distinct packages

spring creek
#

Note that DOTS is not a single package

cosmic rain
#

Data oriented tech stack(dots)

spring creek
#

I shouldn't have said DOTS package above. That was unclear.
I meant the DOTS ecosystem I guess

indigo tree
cosmic rain
#

Just enabling burst doesn't mean you're gonna get any benefit at all from it.

fair jackal
#

Okok

indigo tree
#

I just mean’t if you are already using burst. Though I forget if Unity.Mathematics depends on it or just benefits from it.

golden wave
#

Alright, not sure what else is wrong now 😒
I added the layer to my Character and double checked the spelling

Vector2 direction = (targetPosition - startPosition).normalized;
int layerMask = LayerMask.GetMask("Characters");

RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, 15, layerMask);
Debug.DrawRay(startPosition, direction * 15, Color.red);

if (hit.collider != null)
{
    Debug.Log(hit.rigidbody.gameObject.name);
}```
Not getting anything in my console, so it's not hitting
#

ugh nvm ...
my RigidBody is not on Character but on it's child, works now, thx for all the help

turbid summit
#

Anyone wanna be friends?

nimble pier
thick dune
#

I'm experiencing the oddest thing. Input.GetKeyDown() is not working when I hold consecutive keys down.

For example, Holding Q and W will log Q and W but then I can't log Tab or E but I can press R or any other keys at least 1 space away.

Has anyone experienced this issue?

Edit, my google finally loaded and this is probably a limitation of my keyboard and not Unity.

#

Meh, as long as I know it's a hardware issue and not a Unity issue.

#

Still annoying that the issue exists but it's nice to know that there's nothing I can do about it.

thick dune
#

No, this happens randomly and if 24 specific keys cannot be simultaneously pressed then there is nothing that can be done.

lean sail
#

To be fair, dont think that was specifically the issue in their case. Sounded more like a hardware issue. Im not sure what the video snippet was supposed to be in relation to 24 because I saw the part where it said 6 max

#

If its specifically an issue of not being able to press QWE that's a keyboard issue

thick dune
#

Bawsi is correct. It is a very specific and niche use case for the project I am working on.

swift falcon
#

Guys im gonna explode, i watched so many tutorails, read so many docs, I did everything, but i just cant make a third person camera

#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

swift falcon
#

Nah i tried this docs and vids

#

useless

soft shard
# swift falcon Guys im gonna explode, i watched so many tutorails, read so many docs, I did eve...

What are you actually struggling with? Breaking down your problem into smaller steps usually helps, if its syntax, then refreshing on C# is a good start, I like w3schools C# course for that - the Unity Learn tutorials will teach you how to use the engine and if you follow along with their projects you can have some small examples to play around with too, but when learning anything, its important to understand why it felt "useless" to you, did you actually follow what the videos did and not get the same result and assume its "useless"? Often it could be that you missed a step

cosmic rain
queen saffron
#

sry it might be a dumb question but i started a VR project long time ago and can't figure out where are the speed movement variable. can someone help me with that?

onyx cypress
#

the vignette

gray mural
onyx cypress
#

that one sec

onyx cypress
gray mural
queen saffron
#

I've found it but it doesn't actually speed up the movement for some reason... what could be the reasons behind this?

onyx cypress
gray mural
#

It tells you the namespace does not exist

onyx cypress
#

so im still not sure what to do

gray mural
trail stream
#

why am i being TPed like a few tiles down

#

the code i think worked fine before
player.transform.position = linkedTeleporter.transform.position;

onyx cypress
#

https://hatebin.com/lmmhtlgyuw MY MAin menu works when i first load up the game but doesnt work when the player returns to it after dying? the play or quit button just doesnt do anything

radiant marten
#

if I'm using IBeginDragHandler, IDragHandler, IEndDragHandler to handle dragging, is there a way I can invoke a simulated mouse release? I want to be able to drag an object with left mouse, but if another mouse button is used while dragging it cancels the drag.
eventData.dragging = false; works at canceling the drag, but because it's still registering the original mouse input as being held down it just continues the dragging after the mouse is moved anyways.

spring creek
gray mural
arctic rock
#

I just learned something new today...

Awake() and Start() methods are not called on scripts that are not attached to GameObjects in the scene...

I knew I could have classes that didn't required being attached to a GameObjects and still be accessed... but I didn't realize that meant Awake/Start would not be called on the program start, i guess it makes sense they are not truly initiated, even though their methods are there to be accessed.

I was going mad trying to figure out why it could not find my references....

So the options seem to have them attached to a dummy object the scene. or access my references at runtime when the method is called... that seems inefficient. Seems like the beter option is to have them on a dummy object.. unless I'm missing something.

calm echo
#

@arctic rock What is your use case -- Awake/Start are called on MonoBehaviours and to a lesser used extent Scriptable objects. Those require instances that are attached to gameobjects. Do you just ahve a normal class?

onyx cypress
rugged goblet
gray mural
# arctic rock I just learned something new today... Awake() and Start() methods are not call...

Firstly, if your class is derived from MonoBehaviour, there is a need for neither Awake nor Start to be called, when the script is not attached to the object at the scene.
If you're talking about the normal C# classes, the "Awake" functionality can be implemented in the class' constructors.

Secondly, I don't get your last paragraph. Could you, please, explain the issue in a better way?

spring creek
calm echo
arctic rock
#

Creating a state machine, have individual classes as States that inherit from an Interface. I can access all the methods of the interface. but through testing the awake and start are not being called.

Is adding them to an empty object the way to go?

onyx cypress
calm echo
spring creek
gray mural
#

I have previously mentioned implementing the required functionality in the normal class' constructors

onyx cypress
#

and then it doesnt work

spring creek
#

So what do you mean by "doesn't work" explicitly. With as much detail as possible please

onyx cypress
#

the main menu works at first when the game starts but later on after the player dies from the monster. it goes to the main meny and then it just doesnt do anything when i press it, it doesnt even change color when i hover over it

spring creek
#

Did you accidentally have the eventsystem in DDOL or something?

onyx cypress
spring creek
#

DontDestroyOnLoad

#

I'm guessing no

onyx cypress
#

no

spring creek
#

When you hover over a button, look at the inspector for event system near the bottom. It will show data about events like button hover and click

knotty sun
#

are your button methods on a singleton script

onyx cypress
#

this happens

spring creek
onyx cypress
spring creek
# onyx cypress tf u on about

Please don't speak to me like that.
And look up ONE message above your last one
The one from the user named Steve.... which was an apt question for you...

onyx cypress
knotty sun
# onyx cypress yes they are

well there is your problem, when you reload the menu scene the methods are still pointing at the unloaded menu scene

autumn sandal
#

Ive researched it quite a bit and it would appear this is the way everyone handles toggling between different panels in a main/pause menu? Is there a better way to do this or a way to refactor it? It just kinda seems bloated to me personally but if this is the standard then I guess its not so bad. (Not my script, got the snippet from a unity forum)

public void ShowItem()
    {
        itemPanel.SetActive(true);
        itemHousePanel.SetActive(false);
        itemPetPanel.SetActive(false);
        itemPlayerPanel.SetActive(false);
        currentQuestsPanel.SetActive(false);
        allQuestsPanel.SetActive(false);
        Q001PickFlowerSwordButton.SetActive(false);
        Q002KillTheSpidersButton.SetActive(false);
        Q003CatchHurtButterflyButton.SetActive(false);
        Q001InfoPanel.SetActive(false);
        Q002InfoPanel.SetActive(false);
        Q003InfoPanel.SetActive(false);
        statPanel.SetActive(false);
    }
wide terrace
#

I generally use lists and loops if I need to do something similar

autumn sandal
#

I was afraid that would be the case, ive done a few for loops but I dont fully understand them yet, never done anything with lists.

autumn sandal
# calm echo absolutely not the standard

well, maybe a beginner mistake, I started out doing that and then upon researching to refactor it, everything I found was like that, videos, forums. Seems quite a few people do that

wide terrace
#

As a very overly broad statement, I feel that if I have written code which requires large numbers of very specific references, it's has the smell of poor architecture...

I feel like things should become generic enough, and organized with their own controllers in such a fashion that you don't often need to handle a bunch of different things in very direct and specific ways.

But handling each thing individually as in that screenshot makes sense early on or for prototyping and playing around. Lists and loops would be a reasonable next step

calm echo
spring creek
autumn sandal
autumn sandal
rough tartan
#

do you know why I can't reference my script "FPSController" in my inspector?

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

public class Bullet : MonoBehaviour
{

    public FPSController fpsController;

    void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.tag == "Player")
        {
            fpsController.Hit();
            Debug.LogWarning(collision.transform.root.name);

        }
        Destroy(gameObject);
    }
}

spring creek
#

Show MainCharacters inspector

potent anchor
#

When that happens to me it's usually a compiler error or when i forgot to save a .cs file

#

unity doens't do a great job of complaining that there's a compiler error. It just uses the last good version

#

(in the editor at least)

rough tartan
mossy snow
#

can't reference scene objects from a prefab asset

spring creek
#

Oh, is that a prefab

#

Yes, what reeper said

rough tartan
#

but for exemple if I had multiple MainCharacter in my scene, how my script would know wich one pick ?

radiant marten
radiant marten
scenic thicket
#

Hi, I'm trying to make an inventory system and I'm having some problems not entirely related to the code, let's say I feel like the code doesn't really utilise the power of object orientation. Let's say I have different kinds of items and for each type I want a slightly different system... For example weapons are not stackable, and can have duplicates, materials are stackable and cannot have duplicates... and the UI for the slots is slightly different from type to type. Does anyone have some tips?

mental anvil
#

I have another script to generate a falloff-map. Is there a way to apply the falloff map to the entire terrain without iterating?

indigo tree
#

So you don’t have to get components.

#

You can also have each modifier subscribe to a delegate.

glossy trellis
#

Hello I am new and would like to create a VR app with hands that are detect through the camera for a project. Can you tell me how I could do and/or the steps to follow.Thanks who can't help me !

knotty sun
glossy trellis
#

oh sorry I'm new

knotty sun
glossy trellis
#

ok srry

unique delta
#

Can i make a OnTriggerEnter2D function with a collider that is not attached on the gameobject in wich the script is ?

somber nacelle
#

no, OnTriggerEnter2D will only be called on the object the has the collider (or its rigidbody parent if it has one)
explain the purpose of what you are doing and perhaps a better solution can be suggested

glossy trellis
#

but you know how i can't do it ?

unique delta
#

i don t want to make another script just for that

somber nacelle
#

why do you need another collider for that? can you not just use a physics query?

mental anvil
karmic temple
#

Hi

tight cliff
#

Hello, I was wondering if there was a builtin way in Unity to efficiently get the nearest (or approximate nearest) neighbor?

indigo tree
#

Can you be more specific?

tight cliff
#

I did implemented a spacial hashing grid but I would like to know if there is a builtin way to do that

indigo tree
#

Hashing grid seems like the best way though.

hallow socket
#

Hi guys, im looking for a Domino Board Game tutorial, or something like, have someone did it ou saw something about how to do a domino board game in unity? seems so hard to do

tight cliff
leaden ice
tight cliff
leaden ice
#

you can filter it by layer

#

"efficient" is something that can only be compared to other methods - and the comparison will depend on a lot of factors

#

such as how many such objects there are in the scene

tight cliff
#

Ok I see so its iterating through all objects even those that are very far from the sphere?

leaden ice
#

no

#

The method of storing all the objects in a list is doing that

#

I'm saying you'd compare this method with that one

#

and because that one will be fast if there are few objects, and slow if there are many objects, the comparison depends on the object count

#

it may also depend on other factors - such as how densely populated they are in the scene

tight cliff
#

Oh ok got it

leaden ice
#

etc

indigo tree
#

OverlapSphere requires physics though

leaden ice
#

well it requires your objects have colliders

#

which they may already have

tight cliff
#

Im gonna do some testing, thanks for the suggestions!

leaden ice
#

for various reasons

#

most "interesting" objects will have colliders anyway

tight cliff
#

yes they do

indigo tree
#

If they already have physics then sure.

#

I wouldn’t advise it otherwise but if they do it is fine.

leaden ice
#

I mean basically the nice thing about physics is the queries use spatial data acceleration structures

#

If you didn't have physics already then by far the most efficient algorithm to use would be to store your objects in similar spatial data acceleration structures

#

we're just taking advantage of the already existing one.

tight cliff
leaden ice
#

quadtree is such a structure yes.

#

In 3D it's called OctTree though

#

but there are others. Not sure what PhysX uses, but something like that

tight cliff
#

Ok thanks so its probably way more efficient than my current system 😅

leaden ice
#

probably. The main limitation is just that Unity doesn't directly expose those structures so you're stuck with less than ideal queries like OverlapSphere which don't really answer your question directly.

#

In general though OverlapSphere is a great starting point to get a small list of obejcts which you can then just linearly scan to do the normal "closest distance" algorithm

cold parrot
calm light
#

I guess this is more of an opinion question than anything: How do you handle instances for UI screen? Instantiating each screen as required from and destroying on exit, or pool everything at application start (or scene enter as appropriate) and activate/deactivate as needed?

indigo tree
soft shard
# calm light I guess this is more of an opinion question than anything: How do you handle ins...

I think it depends on the life cycle of the UI your spawning and how generic your elements are - if they are reusable, then a pool makes sense, if they are only ever shown in very specific conditions then spawning and destroying seems fine, if they are toggled often like a inventory then spawning it when the scene loads and destroying it when the scene unloads sounds fine, unless some need to persist across scenes, then spawning it once and keeping it in memory may be a better option, as Mike suggested though, it depends on the complexity of your UI and the lifecycle of what is actually being created to begin with, also if the concern with performance or with design preference as well

indigo tree
#

If you are using the same elements but will different values, like a (character menu for example), you can use the same prefab but use a script to set the values of the elements.

cold parrot
calm light
#

this is not really a question for populating things (I run a MVP architecture with interactor and repository, so all my data lives somewhere completely removed from the UI). But really only for creating new gui objects, potentially en masse (for complex screens) on demand or on load

cold parrot
#

well, creating ui layouts procedurally from scratch without pooling is expensive but, depending on the design, unnoticed or forgiven by the user

calm light
calm light
cold parrot
#

its not really an issue that only affects UI, you should basically pre-allocate, pool or reuse everything in a game

#

instantiate/destroy are not your friends 😉

#

but ofc, you also need to stay productive and there are other concerns like workflow, so ymmv

calm light
#

in which case, what profiler marker does unity utilize to show the layout process? I know there is the canvas layout marker, however what tends to bog frames seems specifically the instantiate call

cold parrot
#

when you deep-profile you will find a lot of time and memory is spent in relayout and text refreshes

calm light
#

unless unity calls it's layout engine twice, once during instantiation and a second time during it's "normal" layout

cold parrot
#

layout should only run once per frame in which changes have happened, unless you manually call it more often

calm light
boreal glacier
#

Would it be a good idea to make a lot of my integral scripts into scriptableObjects (rather than attaching to a blank gameObject in every scene)

#

For instance one script contains a movement check that is used constantly in combat

calm light
#

Depends.

If you need to reference the same instance cross scene and do NOT plan on using addressables/assetbundles, that move can make things a lot easier
If you want to push design work from code into editor, the same goes
If it's just dumb data where some component depends on some instance of values being around, you can also add a [RequireComponent()] attribute to the class that needs said instance

boreal glacier
#

So probably just keep it to player/enemy lists and inventories

lean sail
lean sail
boreal glacier
#

Alright

calm light
#

to add to that, it's a datacontainer that lives outside the scene. So in case you have a lot of entities relying on the same data (say maxhealth or some other set of configurations) it's also a good use, as you only get one instance (or as many as you have assetbundles loaded) instead of one per entity, potentially saving you a lot of memory overhead

boreal glacier
#

Yeah although I do have current battle stats applied directly to the playerStats SO because party switching would make that annoying to keep track of otherwise

lean sail
#

Well regardless you would be reading off the data and copying it to your instance, so its not like you're really saving anything memory wise in this case. Especially required if values can be changed (which would be a majority of cases)

calm light
#

uhhh..... why would you copy something like maxhealth and config data in general?

#
class MyAwesomeHero{
  public MyAwesomeSettingsSO Settings;
  public int MaxHealth => Settings.Maxhealth;
}
``` no copying in sight
#

in addition to skipping the needs to sync for changes in the design data

lean sail
#

Especially required if values can be changed

calm light
#

so all you need to worry about is runtime data living in your objects

calm light
lean sail
#

If for example a buff gave you more max health, suddenly you cant just read off the SO data. I am saying if the data can be changed, you're gonna have to store it anyways

calm light
#

to adjust the example from before

class MyAwesomeHero{
  public MyAwesomeSettingsSO Settings;
  public int MaxHealth => Settings.Maxhealth;
  private int CurrentHealth;

  private void Start()
  {
    CurrentHealth = MaxHealth;
  }
}

there is only one int as member of class MyAwesomeHero

#

... you have to store some of the data (the mutable part) per entity. nothing stops you from sharing the inmutable part

boreal glacier
calm light
#

otherwise you'd have both maxhealth as well as currenthealth on the character and would need to reintroduce the second value case you get some heal effect (health being adjusted both directions)

boreal glacier
#

And have the game calculate it every state change (status start/end, equipment change, etc)

boreal glacier
lean sail
#

I usually just treat SO as a container to read off once then forget it exists. Worrying about the memory here is really a micro optimization imo

calm light
#

it's also a good habit to have as it doesn't cost you anything while helping with memory

lean sail
#

Which is why I called it a micro optimization. Even if this was done for 1000 instances it would have 0 visible affect. And I find it easier to define a plain c# class with all the values I want, then put that inside the SO instead of listing every field. Then whatever uses the data just copy the whole thing. I'm on mobile or I'd try to show more of an example

calm light
#

That's why I called it a good habit. If everything is generally a bit slower than it could be by using a slightly better solution that doesn't cost you, you win in the long run (alongside avoiding doing unnessary work, the fastest code is code that doesn't run after all)

#

I run most of my systems datadriven reading in shit from .csv files in plain c#, but also see to keep what I can shared, deploying what amounts to prototype and flyweight pattern

boreal glacier
#

Would I use one if I need to copy some values over a scene (for example, initiating enemy positions in a fight by taking a number of IDs and spawn locations determined by whatever is causing the fight and putting them through an SO for the script in the combat scene to use)

dusk apex
boreal glacier
#

Yeah Im trying to have a script that allows other scripts to pass data about what enemies are in a fight and where to spawn them (for the initiator script in the combat scene to use)

lean sail
dusk apex
#

Copying data between scenes implies that you're needing persistent data (a save/load system or ddol) and not necessarily an SO (immutable in most practical cases)

clear basin
#

hi chat, help me pls
should this line work?
script1 = transform.parent.gameObject.GetComponentInChildren<Script1>();
i wrote this in Start method, all objects exist, all scripts were attached but it doesn't find needed script

rigid island
#

or you're looking on the wrong obect

#

anyway should just make a field and link this in the inspector

lean sail
#

I always find it questionable to use .parent or like search through children at runtime. Seems very fragile

rigid island
#

yea same

#

if its on the same object i rather keep the reference in the script as a field

#

then make a public getter if i need it else where

clear basin
rigid island
clear basin
clear basin
rigid island
clear basin
rigid island
clear basin
rigid island
clear basin
#

i mean, if i assign the parent's script through inspector, will it assign the copied parent's script to the child?

#

@rigid island

rigid island
#

nothing gets "copied"

#

references are linking to the specific component , you can drag it into any other script , it just all leads to the same one

lean sail
clear basin
mellow barn
clear basin
mellow barn
#

so I'm doing a multiscene project and the audio plays when expected on the first run using this code...

    {
        // Call your method to reset triggers here
        Run();
    }

    // Start is called before the first frame update
    void Run()
    {
        instance = this;
        PlayerPrefs.SetInt("Level", level);
        scoreText.text = "Score: 0";
        multiText.text = "Multiplier: x1";
        phase = Phase.OPEN;
        dialogueBox.SetActive(true);
        if(healthFill != null){
            healthFill.color = Color.Lerp(Color.red, Color.green, healthBar.value / healthBar.maxValue);
        }
        dialogue.InitDialogue(phase);
    }```

the last click of the dialogue (init dialogue)  involves running this function:

public void TerminalButtonPress(){
if(phase == Phase.OPEN){
theMusic.Stop(); //this didnt matter before, but it totally does during resets w pause button
theMusic.time = 0;
theMusic.Play();
playing = true;
noteScroller.started = true;
}
else if(phase == Phase.CLOSE){
levelSummary.SetActive(true);
}
}```

on the first run, this works as expected. on the second, for instance, if i pause, return to home menu, and then enter the scene again, well, first of all, audio doesn't play on awake when i enter ANY scene for the second time. which is Very Unsettling. second, when i run this code a second time, the music does NOT play. if i debug in that function, it claims it's playing, but by update, it is not playing for some reason. no code touches turning off the audio.

mellow barn
# clear basin yes and then use ctrl + d

ctrl+d? wait, are you spawning this at runtime? if so, it should be able to access the script, yes (assuming it is the same object, as in, you are spawning a prefab or something similar)

#

but it seems like you might be assigning a script to one child, then creating a new object which is also the parent of the same child-- in that case, no, that wouldn't work. it needs to directly have the script attached

somber nacelle
clear basin
mellow barn
clear basin
#

so bye

mellow barn
somber nacelle
#

you said this happens when you pause and go back to the main menu. are you perhaps setting the time scale to 0 when you pause? and just not setting it back to 1 when you return to the menu?

mellow barn
#

Oh fuck. Let me check that 😭😭😭😭

mellow barn
void bison
#

is there a way to make child classes inherit an editor function called on a parent class

drowsy steeple
#

I am trying to edit a mesh at run time like this:

            foreach (var v in vertices )
            {
                if (Vector3.Distance(v, contactPoint) <= damageRadius)
                {
                    continue;
                } else newVertices.Add(v);
            }
            var uv = new Vector2[newVertices.Count];
            mesh.uv = uv;
            mesh.Clear();
            mesh.vertices = newVertices.ToArray();
            mesh.RecalculateBounds();
            mesh.RecalculateTangents();
            mesh.RecalculateNormals();

However the mesh just becomes invisible - ultimately I am trying to get a sort of dynamic destruction type thing going on

#

Any ideas?

cosmic rain
#

Also, you can double click the new mesh in the mesh filter to inspect the mesh attributes.

cosmic rain
indigo tree
drowsy steeple
#

Any good tutorials i should watch?

indigo tree
cosmic rain
#

Well, that's basically what they're doing. Modifying the mesh in code.🤷‍♂️

#

That enters the "procedural generation" category.

indigo tree
#

Kinda ig.

#

IIRC modifying meshes can lead to lots of garbage collection, hence why I recommended full procedurals

#

@drowsy steeple what are you trying to achieve exactly btw?

cosmic rain
#

It's still not clear what you mean by "procedurals" or "full procedurals". I never heard that term being used like that.

drowsy steeple
#

a dynamic destruction system that is similar to r6 siege

#

obviously not on the same level or thoroughness because im not there yet

#

but something similar

#

lol

indigo tree
indigo tree
#

That is out of my area of expertise. Though I do know a asset store package for that if you want it.

#

Sorry I though you were going for something completely different. 😅

indigo tree
#

Have not used it myself but it has good reviews.

drowsy steeple
drowsy steeple
#

The mesh shows that it is read and write but could it be possible that the instance of it in the scene isnt?\

#

maybe i placed it down before i switched it to read/write

cosmic rain
#

Placing an object with the mesh in the scene doesn't create a new copy of the mesh. it references the asset data.

drowsy steeple
#

thats what i thought

#

was just hoping it was something simple like that 😭

cosmic rain
#

You never said anything about my initial message though.

#

Or shared any debugging results.

drowsy steeple
#

i updated it to attempt to recalculate tris:

       Vector3 localContactPoint = transform.InverseTransformPoint(contactPoint);
       Debug.Log($"Local Contact Point: {localContactPoint}");

       Vector3[] vertices = mesh.vertices;
       int[] triangles = mesh.triangles;
       Vector2[] uvs = mesh.uv;

       Debug.Log($"Original Vertices Count: {vertices.Length}");
       Debug.Log($"Original Triangles Count: {triangles.Length / 3}");

       List<Vector3> newVertices = new List<Vector3>();
       List<Vector2> newUVs = new List<Vector2>();
       List<int> newTriangles = new List<int>();
       Dictionary<int, int> vertexMap = new Dictionary<int, int>();

       // Visual debugging: Draw damage radius
       Debug.DrawRay(contactPoint, Vector3.up * damageRadius, Color.red, 2f);

       // Keep track of vertices within the damage radius
       for (int i = 0; i < vertices.Length; i++)
       {
           if (Vector3.Distance(vertices[i], localContactPoint) > damageRadius)
           {
               vertexMap[i] = newVertices.Count;
               newVertices.Add(vertices[i]);
               newUVs.Add(uvs[i]);

               // Visual debugging: Draw kept vertices
               Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.green, 2f);
           }
           else
           {
               // Visual debugging: Draw removed vertices
               Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.red, 2f);
           }
       }

       // Log new vertex count
       Debug.Log($"New Vertices Count: {newVertices.Count}");

       // Update triangles to use the new vertex indices
       for (int i = 0; i < triangles.Length; i += 3)
       {
           int v0 = triangles[i];
           int v1 = triangles[i + 1];
           int v2 = triangles[i + 2];

           if (vertexMap.ContainsKey(v0) && vertexMap.ContainsKey(v1) && vertexMap.ContainsKey(v2))
           {
               newTriangles.Add(vertexMap[v0]);
               newTriangles.Add(vertexMap[v1]);
               newTriangles.Add(vertexMap[v2]);
           }
       }

       // Log new triangle count
       Debug.Log($"New Triangles Count: {newTriangles.Count / 3}");

       // Update the mesh
       mesh.Clear();
       mesh.vertices = newVertices.ToArray();
       mesh.uv = newUVs.ToArray();
       mesh.triangles = newTriangles.ToArray();
       mesh.RecalculateBounds();
       mesh.RecalculateTangents();
       mesh.RecalculateNormals();```
#
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent      : Original Vertices Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent      : Original Triangles Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent      : New Vertices Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent      : New Triangles Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent      : Destruction Log 6```

This is what the logs show
#

granted i did ask chatgpt for help recalculating the tris so that might be source of error

cosmic rain
drowsy steeple
#

GetComponent<MeshFilter>().mesh

#

The monobehaviour is on the same gameObject as the meshfilter

cosmic rain
half cosmos
#

can i subscribe to another GameObject's OnMouseDown?

    private void foo() {
        Debug.Log("callback worked");
    }

    private void bar() {
        GameObject gObj = Instantiate(gObj, Vector3.zero, Quaternion.identity);
        gObj.OnMouseDown.AddListener(foo);

this doesn't actually work because gObj is a GameObject, not the class defined in gObj's script component.
but can i do something similar to this?

spring creek
#

OnMouseDown is not an event, it is a callback. So no

#

You can call a method in another script FROM OnMouseDown, or invoke an event from it

#

That is the closest you will get

half cosmos
#

yeah i was also considering invoking an event from OnMouseDown

#

but i wouldn't have a reference to that event

cosmic rain
#

Make it so you do have

half cosmos
#

i'm struggling to see how to do that, since i can't pass an event through Instantiate()

calm light
#

you have a GameObject reference. you can just attach a monobehaviour to it that implements IOnMouseDownHandler and publishes an event when that happens, just subscribe in bar() when you fetch it

half cosmos
#

this sounds promising

#

i need some time to understand this

rigid island
calm light
#

why make it so complicated tho?

#

public class EventSource{
  public event Action SomeEvent;
}

/*somewhere else where you want to subscribe*/
...
eventsource.SomeEvent += SomeEventFunction; // eventsource is an instance of EventSource
...
#

the event keyword is specifically made so you can fiddle with other entries on it but only add or remove yourself

#

no need for big init function where you pass stuff in or whatever

half cosmos
#

is this a different solution to the one you mentioned above?

calm light
#

nah, it's the same

#

EventSource just missing the interface and monobehaviour inheritance

spring creek
#

Foo instance = Instantiate(prefab)
instance.init(eventRef)

This seems way less complex to me

half cosmos
#

i think i understand that better

calm light
#

it also obscures what happens there if all you do is subscribing to an event

spring creek
#

No it does not

calm light
#

init does not tell me what happens there, I have to look at the implementation

#

init just tells me it inits something

spring creek
#

So look at the implementation... but you can just make a summary....

#

Still far less complex and more foolproof

calm light
#

but why should I if I can, you know, use a specific language feature of c# and not jump needlessly through the codebase?

spring creek
#

Because it is easier and more straightforward?

calm light
#

it's not. that is my point

spring creek
#

It's not in your opinion

#

I disagree. I gave up on the way you recommend quite a while ago because it just doesn't cut it most of the time

calm light
#

¯_(ツ)_/¯

cosmic rain
half cosmos
calm light
#

the orginal question was: how do I subscribe to an event

#

I replied: event += eventhandler

#

somehow that is too complicated

#

excuse me for being confused

cosmic rain
#

I think the issue is that they don't just want to subscribe to an event. There's more context to the issue that was not clarified correctly to us

spring creek
#

I was responding to your response about init being to complicated. Which ..... how?
It is obviously not

drowsy steeple
cosmic rain
#

Or just use the debugger and step through the code

calm light
spring creek
lean sail
#

rather than going through GameObject

half cosmos
#

how do you ... drag something into code?

lean sail
#

in inspector

calm light
#

anyhow, given how deeply this is steeped in opinion and people deciding to bring up perceived past slights, I'll take my leave

#

glhf

half cosmos
#

i'm kind of getting lost in all the different options

#

i'm not sure which option to follow

cosmic rain
spring creek
half cosmos
#

maybe i'll just try init because i seem to understand it best at this point

lean sail
#

either one works, i tend to directly call methods if I can.

half cosmos
#

i thought the init method was also using an event

spring creek
half cosmos
#

yeah

spring creek
#

You could also skip the event and just call the end method directly instead of init or subscribing

half cosmos
#

mmm that might have more complications because of the context

#

because the children objects don't know which child they are

#

so i'd have to tell them somehow

lean sail
#

thats completely a new problem from what youve initially described of just not being able to "subscribe" to a unity message

half cosmos
#

yes

#

so probably best to use one of the approaches using events

spring creek
#

This is some of the missing context that dlich was talking about

half cosmos
#

oh... i can give context but i need to think about how to explain it

spring creek
cosmic rain
#

Think first => give context => ask question.

Not the other way around

half cosmos
#

yes by all means there may be a better approach than what i've asked about

#

okay i can also send code

cosmic rain
drowsy steeple
#

On the collision it shows that it has 0

cosmic rain
drowsy steeple
#
   private MeshCollider collider;
        private MeshFilter meshFilter;
        private Mesh mesh;
        public void Awake()
        {
            Debug.Log("Destruction Log 1");
            collider = GetComponentInChildren<MeshCollider>();
            meshFilter = GetComponent<MeshFilter>();
            mesh = meshFilter.mesh;
            //    item = GetComponent<Item>();
            //     item.mainCollisionHandler.OnCollisionStartEvent += CollisionHandler_OnCollisionStartEvent;
            Debug.Log(mesh.name);
            Debug.Log(mesh.vertices.Length);
            Debug.Log("Destruction Log 2");
        }

        void OnCollisionEnter(Collision collision)
        {
            float damageRadius = 1.5f;
            Vector3 contactPoint = collision.contacts[0].point;
            Vector3 localContactPoint = transform.InverseTransformPoint(contactPoint);
            Debug.Log($"Local Contact Point: {localContactPoint}");

            Vector3[] vertices = mesh.vertices;
            int[] triangles = mesh.triangles;
            Vector2[] uvs = mesh.uv;

            Debug.Log($"Original Vertices Count: {vertices.Length}");
            Debug.Log($"Original Triangles Count: {triangles.Length / 3}");

            if (vertices.Length == 0 || triangles.Length == 0)
            {
                Debug.LogError("Mesh has no vertices or triangles!");
                return;
            }

            List<Vector3> newVertices = new List<Vector3>();
            List<Vector2> newUVs = new List<Vector2>();
            List<int> newTriangles = new List<int>();
            Dictionary<int, int> vertexMap = new Dictionary<int, int>();

            // Visual debugging: Draw damage radius
            Debug.DrawRay(contactPoint, Vector3.up * damageRadius, Color.red, 2f);

            // Keep track of vertices within the damage radius
            for (int i = 0; i < vertices.Length; i++)
            {
                if (Vector3.Distance(vertices[i], localContactPoint) > damageRadius)
                {
                    vertexMap[i] = newVertices.Count;
                    newVertices.Add(vertices[i]);
                    newUVs.Add(uvs[i]);

                    // Visual debugging: Draw kept vertices
                    Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.green, 2f);
                }
                else
                {
                    // Visual debugging: Draw removed vertices
                    Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.red, 2f);
                }
            }

            // Log new vertex count
            Debug.Log($"New Vertices Count: {newVertices.Count}");

            // Update triangles to use the new vertex indices
            for (int i = 0; i < triangles.Length; i += 3)
            {
                int v0 = triangles[i];
                int v1 = triangles[i + 1];
                int v2 = triangles[i + 2];

                if (vertexMap.ContainsKey(v0) && vertexMap.ContainsKey(v1) && vertexMap.ContainsKey(v2))
                {
                    newTriangles.Add(vertexMap[v0]);
                    newTriangles.Add(vertexMap[v1]);
                    newTriangles.Add(vertexMap[v2]);
                }
            }

            // Log new triangle count
            Debug.Log($"New Triangles Count: {newTriangles.Count / 3}");

            // Update the mesh
            mesh.Clear();
            mesh.vertices = newVertices.ToArray();
            mesh.uv = newUVs.ToArray();
            mesh.triangles = newTriangles.ToArray();
            mesh.RecalculateBounds();
            mesh.RecalculateTangents();
            mesh.RecalculateNormals();
cosmic rain
#

Huh. Where does it show 13564 then..?

spring creek
#

This is way too much code to put in directly.
3-5 lines is ok for formatting usually

drowsy steeple
#

first length debug is the 13k, 2nd in the collision, is 0

#

mb

cosmic rain
half cosmos
#

basically i have a GameObject that's sort of like a machine with different controls on it, and displays. The controls and the displays are child GameObjects created by the parent's Start() function. when the controls are clicked on, the machine needs to display the right output. this is the code on the parent object

drowsy steeple
#

still shows the new as being 0

half cosmos
cosmic rain
drowsy steeple
#

Oh i see now, the 0's are coming from collisions that happen after the initial facepalm

cosmic rain
#

As for the new vertices, you don't add all the existing vertices to it.

drowsy steeple
half cosmos
spring creek
half cosmos
#

but i mean

#

it's not capitalized?

#

like Start()

spring creek
half cosmos
#

it goes in the script right?

spring creek
#

Name it RaInBoW() for all it matters

spring creek
half cosmos
#

wait how does this solve my problem...

spring creek
#

When it invokes, you know MouseDown was called

half cosmos
#

but we're talking about two different scripts here, right?

spring creek
#

Yes

#

That was your original question, right?

half cosmos
#

so the init function goes in which script, the one with OnMouseDown()?

#

yes

spring creek
#

Why would it go in the one with MouseDown?

half cosmos
#

because mouse down needs to invoke the event...

spring creek
half cosmos
#

okay

spring creek
#

You CALL init from the mouseDown script

#

But it is defined and implemented in the other

half cosmos
#

how does it get a reference to init?

spring creek
#

You have to get the reference to the script at some point

half cosmos
#

how?

spring creek
#

That is needed no matter which method you use of course

spring creek
half cosmos
#

oh oh this is good

#

yeah this is really good

#

thanks

#

i probably want a serialized reference or DI

spring creek
half cosmos
#

the serialized reference section talks about the inspector

#

i don't think i can do that, since i'm instantiating the GameObjects in code

#

right?

spring creek
#

Correct

sleek bough
spring creek
#

Instantiate returns a reference, like I showed in the example code

sleek bough
#

Serialized reference Aethenosity mentioned will be in that case in the instatiating object

#

Or in another manager that will initialize it in turn

half cosmos
#

so which code goes in the instantiated object's script?

cosmic rain
half cosmos
#

Assets/Permutor/ManagePermutor.cs(68,20): error CS1061: 'GameObject' does not contain a definition for 'Init' and no accessible extension method 'Init' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

somber nacelle
#

you need to be using the correct type for your variables rather than just GameObject

half cosmos
#

oh

#

it's a prefab

spring creek
somber nacelle
half cosmos
#

what's the type?

somber nacelle
#

how should i know? its your code

spring creek
#

MyScript prefab
MyScript instance = Instantiate(prefab)
instance.NameOfMethod()

spring creek
rigid island
half cosmos
#

no no i know what types are

rigid island
#

then you should know what to change it to

spring creek
#

Well then you should know that we cannot answer that question

half cosmos
#

oh you're instantiating a script?

somber nacelle
#

no, you are instantiating a prefab. but you can refer to it using any of the components on the root of the prefab

#

just like literally any other object you can (and should be) reference the components directly

cosmic rain
#

You're instantiating a prefab together with whatever is attached to it(including your script)

rigid island
half cosmos
#

is the type the name of the prefab?

#

like the filename?

spring creek
somber nacelle
spring creek
#

It is the class, as navarone said

half cosmos
#

i thought so too...

#

types are int, string, etc

spring creek
half cosmos
#

a script with the filename foo has type foo?

somber nacelle
spring creek
#

Filename is irrelevant

somber nacelle
half cosmos
#

oh it's the name of the class defined in the script?

somber nacelle
#

classes are types. so yes.

half cosmos
#

yes

#

i have confusion because game objects are not synonymous with scripts

spring creek
#

GameObjects are types

half cosmos
#

but ok let me try the name of the class

spring creek
#

Script is a near meaningless word that just means file. It confuses many people

rigid island
#

gameobject is just a glue that holds all the components on it

spring creek
#

Get in the habit of just calling them classes

rigid island
spring creek
rigid island
#

Unity Object, so only MB or alike, in case of instantiate

#

confusing enough there is the c# Object base class

#

I wouldn't have minded a UObject baseclass

storm wolf
#

Do you guys ever make empty monobehaviors to put on gameobjects? like either to identify them or some other reason? if so what reasoning?

summer heart
#

GameObject is unity's "container?" object class. Game objects contain a list of a components (a.k.a. scripts). You can reference a game object through one of its components.

rigid island
#

sure

summer heart
half cosmos
#

maybe i should move to the beginner channel

storm wolf
rigid island
storm wolf
#

for what reasoning?

rigid island
#

because I rather use type-safety than tags/strings

storm wolf
#

ok makes sense yeah

#

didn't know if it was bad practice or anything I was gonna make one wanted to check in here first though to test the waters

summer heart
#

same. I've used empty monobehaviours for when I need multiple tags on a single object (and then sometimes they become event busses)

rigid island
#

also TryGetComponent is soo much more convienent than doing
if(other.CompareTag)
var comp = other.GetComponent
if(comp != null) etc.

storm wolf
#

very true

spring creek
#

Oh.... too slow lol

fair jackal
#

Isn’t getcomponent a lot slower though?

#

Or is trygetcomponent just so much faster than get component

rigid island
#

it just does the same thing plus a null check

spring creek
somber nacelle
#

TryGetComponent is not any faster than GetComponent, it just combines the GetComponent and the null check and also doesn't allocate anything in the editor when the component does not exist on the object unlike GetComponent which allocates an instance to throw MissingComponentExceptions

fair jackal
#

How about compared to checking tags

spring creek
#

Checking tags is gonna be faster

fair jackal
#

Ah

spring creek
#

Tags just.... suck

fair jackal
somber nacelle
fair jackal
#

Ah okok

summer heart
#

you should only really be getting a component on events like on collision. The difference could only really be meaningful if your doing like 1000 at once or running it every frame.

fair jackal
#

Ah ok got it

rigid island
fair jackal
#

Then is it usually a bad sign if getcomponent is running every frame, but i still need the component

somber nacelle
#

i mean, if you are just getting the same component over and over, just cache the reference instead of calling GetComponent every frame

fair jackal
#

Well i mean if it’s not guaranteed to be the same object’s component

spring creek
summer heart
somber nacelle
fair jackal
#

Ok then

somber nacelle
#

GetComponent is not very slow so there's not much harm in calling it every frame if you need to, but if there is no reason to call it every frame then don't. but the same can be said of literally any operation that doesn't need to happen every frame

summer heart
fair jackal
#

Refactoring?

summer heart
#

and yeah get component is just a list iteration (which will usually only be max 10 elements), it's not likely to be a big bottleneck

rigid island
#

I got some of my OverlapsNonAllocs inside varying polling timings

#

some can be even just every 0.01 sec etc.

fair jackal
#

I see i see

spring creek
fair jackal
#

Ah okok

#

Imma look into all this optimizing stuff later, thanks guys 😄

somber nacelle
# somber nacelle GetComponent is not very slow so there's not much harm in calling it every frame...

Here is some actual data to back up the claim that GetComponent is not slow.
Code used for the tests

1 GetComponent call on an object measured 100 times had a max time of 0.01ms (or 1/1000 of a frame at 100 frames per second)
100 GetComponent calls in a loop on the object maxed out at 0.6ms (or 6/100 of a frame at 100 frames per second)
1000 GetComponent calls maxed out at 3.9ms (or about 39/100 which is only a bit more than 1 third of the frame at 100fps).

It isn't a super comprehensive test, and only tests using GetComponent on an object with 10 components added in a random order as well as getting the same component over and over, but it does at least show that this operation is pretty fast and doesn't really need to be worried about too much.
Of course, like any operation, if you can avoid repeating it, then do so.

young tapir
#

Is there a way to loop through every GameObject in a scene via a script, without inheriting from MonoBehavior/something close?

#

Everything I can find on the wiki shows me the typical way of just using GetComponents<T> but, not how without a component active

somber nacelle
#

before I provide an answer to that, I gotta ask why you would want to do that

young tapir
#

The GameObject I need is active in the scene somewhere, but I can't access it looking in the hierarchy, I have to get at its Skinned Mesh Renderer

#

It's an incredibly specific case but.. Hopefully a pretty general concept

somber nacelle
#

it's going to be incredibly fucking slow compared to getting the reference to that object properly, but you can get all of the root gameobjects of a scene and foreach over their transforms (and their child transforms recursively all the way down).
Provide more details about your actual use case and a proper solution can be suggested

lean sail
#

Even without knowing the context, I'd claim that this isnt an incredibly specific case. You've just chosen to do something backwards

young tapir
#

If I could add a component to the gameobject and be done with it, I would

somber nacelle
#

until you actually give any actual details there's no point in arguing your case about why this is necessary. everyone is going to (rightfully) assume it isn't necessary

lean sail
young tapir
# somber nacelle until you actually give any actual details there's no point in arguing your case...

Somewhere in the scene, Dalg_Chestplate_Armour is added, and then applied to the player as armour like this, I need to get at it and edit the emission values of the sharedMaterial. I've looped through the main parent of the "creature" it's added to and debuged every name and it's just not added. Which means for all intents and purposes I can't get at it without checking the whole scene.

I'm sure there's an easier method that's more performant but it happens once, when you're not even able to see what's going on.

#

Chestplate 1 is what I need, that has the SMR.

somber nacelle
#

is this some modding bs or can you not just look through your own code to see where it may be instantiated from?

young tapir
#

It is some modding bs

somber nacelle
#

then go ask for help in the game's modding community

young tapir
#

I'm asking how to loop through gameobjects in a scene without inheriting from monobehavior, not how to do my specific thing

somber nacelle
#

and your question is because you want to do that specific thing instead of figuring out how to do that thing correctly

young tapir
#

Do you even know if it's the correct way?

lean sail
#

What you're doing is most definitely not the correct way

somber nacelle
#

i can assure you that iterating through every single object in the scene is very likely not the correct way

young tapir
indigo tree
young tapir
#

I'm only curious how

indigo tree
#

I believe

indigo tree
#

Don’t ever do this though

lean sail
#

The scene directly has a method to get root objects

young tapir
#

I am fully aware it is a horrible idea to do it

lean sail
half cosmos
#

Thanks for the help everyone, it worked 😮
once i changed the type from GameObject to something more specific, i was able to call methods in the instantiated object's script
then i passed a function reference to the instantiated object, which it could call when it got an onclick event

young tapir
#

The best method would be to add a monobehavior in the editor and just use that, but i can't

indigo tree
lean sail
#

Also couldnt you just GameObject.Find it based on name?

young tapir
indigo tree
#

I see.

young tapir
#

This would probably give a few people a heart attack lol

#

And it didn't even work angry_laugh_cry

indigo tree
#

Naming variable m?

lean sail
indigo tree
indigo tree
#

So you don’t have to iterate

young tapir
#

Not everything is "ignoring"

lean sail
#

well ignoring, not reading, about the same thing. Boxfriend did answer your question as well for what you initially wanted #archived-code-general message

#

but really, ask questions like this to the games modding community. either they have a system in place to get you exactly what you need, or they'll tell you to use GameObject.Find

young tapir
#

I did ask them, I asked the people who made the game

#

Well, one of the devs, not all of them

#

GameObject.Find also did not get the GameObject, I debugged it and it was null.

somber nacelle
#

then that object was either inactive or non-existant at the time you called it. or you spelled the name incorrectly

sonic kite
#

Hi, for some reason I am unable to paint on terrain, any possible reasons why this may be?

lean sail
#

If you're doing it with code then you should specify and show relevant code

glad sentinel
#

A friend of mine is talking about dropping her course bc she struggles to remember code and has to watch a lot of tutorials for coding
I keep telling her, there's no shame in following videos but its a real weight 😦 sad

#

I was the same in uni, most of my course I spent following tutorials

cold parrot
glad sentinel
#

I graduated a year ago

#

And no I meant like
I struggled to remember my classes so anything I made for fun, I would watch video tutorials to supplement what I couldnt remember

#

The classes werent just watching videos, good lord

cold parrot
#

if the school doesn't force you to understand the concepts and apply them to problems for which no tutorials exist, you have not spent your time well

glad sentinel
#

Oh my God
Kurwa
I just mean like forgetting the syntax, not the concept of implementation
When I'm writing in HLSL, and I forget a line, I just look up a tutorial

#

Its stuff for fun not training for the Air Force

cold parrot
glad sentinel
#

Idk, cant be bothered

#

Coding to me is a case of "hehe I made something cool"

fading umbra
#

I don't understand how to fix some flaws in this script. Today I can't think like I would usually. I have been stuck on this for quite some time now. How can I make it so it doesn't drop the current weapon if it is not the same type? I have 3 types of weapons, Primary, Secondary, and Melee.

https://hastebin.com/share/enifugufan.csharp

tawny elkBOT
fading umbra
knotty sun
#

yes, if you want people to read your code, post it correctly

fading umbra
#

Ok

steep herald
#

Is there a way to hook directly onto the space partition unity creates for the physics simulation?

steep herald
knotty sun
indigo tree
knotty sun
steep herald
#

jeez guy

radiant marten
indigo tree
#

lol

floral needle
#

Hey can someone help me with this:
I'm trying to record the plays each player makes in my game for later debugging and other purposes and for PC this is pretty straightforward, I just give a filepath and done. My issue is with the Android build, the path that I use (Application.persistentDataPath + wtv name) is not easily accessible, is there a way for me to use/create a more accessible folder on mobile?

#

Code for ref:

   private void Start()
    {
        // Determine the folder path based on the platform
#if UNITY_ANDROID || UNITY_IOS
        _writeToFolderPath = Application.persistentDataPath;
#else
        if (string.IsNullOrEmpty(_writeToFolderPath))
        {
            // Set to a default path inside the game installation folder if no path is provided
            _writeToFolderPath = Path.Combine(Application.dataPath, "GameRecords");
        }
#endif
        if (!_writeToFolderPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
        {
            _writeToFolderPath += Path.DirectorySeparatorChar;
        }

        string fileName = $"GameRecord_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.json";
        _filePath = Path.Combine(_writeToFolderPath, fileName);

        // Ensure the directory exists
        try
        {
            if (!Directory.Exists(_writeToFolderPath))
            {
                Directory.CreateDirectory(_writeToFolderPath);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"Failed to create directory {_writeToFolderPath}: {ex.Message}");
            this.enabled = false; // Disable the script if directory creation fails
            return;
        }
    }
leaden ice
#

unless you mean something else by "not accessible"

#

btw with cs if (!Directory.Exists(_writeToFolderPath)) { Directory.CreateDirectory(_writeToFolderPath); }
You don't need the if statement at all

floral needle
leaden ice
#

what is file manager

floral needle
#

the normal phone app file manager

leaden ice
#

Sounds like some particular app

#

Why not just grab it through ADB

dim umbra
#

Is it possible to be able to assign a script in the inspector for another script to run a function in? I have a basic UI manager script and it would be convenient to be able to write a separate script for whatever each button does, then run a function in that script through the UI manager (probably explaining this very poorly, sorry)

leaden ice
#

but maybe you're asking about UnityEvents

dim umbra
leaden ice
dim umbra
#

What I meant was to not have to specify the exact script in the manager, so I could write different scripts after to do different things

#

but again, this should work

vale bridge
#

Why is unboxing faster than boxing? Is it because boxing involves creating new objects which take time? Is that it to the discussion? In an interview I was asked what the relation between GC and boxing/unboxing was and the only thing I could come up with was that boxing involved creating new Object objects which required memory allocation on the managed heap, and nothing else(that I know of that's related).

leaden ice
#

or rather a new section of the heap

#

it's creating an object

vale bridge
#

mhm

leaden ice
#

unboxing is just dereferencing the pointer