#💻┃code-beginner

1 messages · Page 505 of 1

stuck palm
#

how can i make my unity window go orange like this when something happens out of focus?

steep rose
#

I believe it does do that already

#

you just cant be tabbed into it, and you have to start the application

#

also may i ask why? thats kinda strange that you would want that

#

also this is not a code related question, or unity at all

ivory bobcat
#

Cache the local euler angle property, modify it then reassign it to the local euler angle property. For example: cs var lea = transform.localEulerAngles; lea.x = ... transform.localEulerAngles = lea;
Assuming you're simply having difficulties with c# properties relative to Unity's strange naming convention for properties - they're camelCase and not Pascal for some reason..

stuck palm
#

im talking about like my built project

steep rose
#

thats a windows thing

stuck palm
#

not the editor

steep rose
#

not a unity thing

#

windows already does that normally iirc

stuck palm
#

im talking about based on a unity event

#

like if youre tabbed out and you load into a game

#

you send an event or whatever

steep rose
#

but as stated its not a unity thing

#

afaik

#

you can write your own code via c++ or python or something do mess with windows if you really want that

#

its most likely possible, i just dont know how

lethal elbow
steep rose
#

you can also clamp various ways using custom logic and such

#

i dont do that though

lethal elbow
#

I probably should have gone straight to the documentation without asking

lethal elbow
steep rose
#

then use the documentation

iron wing
#

where is a good place to ask about my ide?? everytime I open a script (at least i think thats whats happening) it looks like I can't use autocomplete. only way for it to show up again is reopening visual studio code. this is really getting on my nerves now :(

eternal falconBOT
steep rose
iron wing
# steep rose !ide

oddly enough i've already followed all the steps for that. it works fine but every now and then it stops and I've gotta relaunch vs for the unity extension to work properly.

languid spire
iron wing
languid spire
#

that's why, remove VS Code

iron wing
#

like uninstall the whole thing?

languid spire
#

yep

steep rose
iron wing
iron wing
lethal elbow
# ivory bobcat Cache the local euler angle property, modify it then reassign it to the local eu...

The last line of this is stopping the rotation of my object

  Vector3 pitch = transform.localEulerAngles; 
                
                currentMousePosition = Input.mousePosition.y;
                mouseMovement = currentMousePosition - startMousePosition;

                transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);

                pitch.x = Mathf.Clamp(pitch.x, -30f, 30f);


                startMousePosition = currentMousePosition;

                transform.localEulerAngles = pitch;
#

Nevermind im a dummy, I rearranged everything to the top 🙂

languid spire
#

why would you do a Rotate and set the eulerAngles at the same time?

ivory bobcat
lethal elbow
#

There is an issue where the object gets to 0 on rotation.x and then it jumps to the max clamp value

ivory bobcat
#

Euler angles acquired from the property (a Quaternion) would vary.

languid spire
ivory bobcat
lethal elbow
steep rose
#

read from the localrotation of the transform

lethal elbow
#
                Quaternion pitch = transform.localRotation;
                pitch.x = Mathf.Clamp(pitch.x, -30f, 30f);
                transform.localRotation = pitch;
                

Like this?

short hazel
#

Quaternions don't store angles in degrees, so that won't work

lethal elbow
#

It did not work as said haha

short hazel
#

One Quaternion can be represented by multiple different Euler Angles. So you shouldn't be reading from .eulerAngles at all, since the values you get can vary wildly

#

Store the rotation in a vector variable (or two float variables), and accumulate the mouse rotation into that. Then clamp and apply to .eulerAngles once

queen adder
#

Is it possible to refrence a Monobehavior script on a Non monobehavior script

short hazel
#

Yes, MonoBehaviour is a type like others

#

Just make a variable of that type (or the precise script type you need)

rich adder
#

just keep in mind you have no inspector so you have to pass the reference somehow so its not null

queen adder
rich adder
#

simple DI with a method

queen adder
#

DI?

short hazel
#

Or a constructor

wintry quarry
#

You almost certainly want to use your actual script class and not MonoBehaviour

tiny bloom
#

im detecting right clicks on objects in canvas
i instantiate a UI prefab
the parent has an image with 0 alpha, to detect clicks and there's children as shown

however when i right click the child image, it detects the child image first before detecting the image component on the parent gameObject
i understand this is the normal behavior of unity
but I want a clean way to change that.

this method returns all the item that the raycast passed through after i pass it the pointer click data

 List<RaycastResult> GetClickedItems(PointerEventData eventData)
 {
     List<RaycastResult> results = new List<RaycastResult>();
     graphicRaycaster.Raycast(eventData, results);

     return results;
 }
rich adder
#

you also have the static functions like FindObjectOfType if you don't need specific one, or its the only one. Or use the array version loop through them to find specific thing. Using injection is always better (pass it through a method like constructor too)

wintry quarry
#

If not just disable Raycast target on it

queen adder
tiny bloom
rich adder
short hazel
#
class Sample
{
    public YourScript Script { get; }
    
    // Constructor
    public Sample(YourScript script)
    {
        Script = script;
    }
}

// Usage:
Sample s = new Sample(someScript);
#

Simple constructor injection

rich adder
#

cause one way or another you still need to grab that specific mb component, we don't know your setup so its hard to say how exact

lethal elbow
short hazel
#

Yes any of them

#

The read is the problem

#

x = t.eulerAngles;

queen adder
rich adder
#

this script ?

queen adder
#

Yes the script clickDetection

#

I dont have that yet I just wrote the code

rich adder
#

still confused on why you're passing it for tbh

lethal elbow
short hazel
#

None of them. Do NOT read euler angles

#

Only write to them

queen adder
rich adder
queen adder
#

!code

eternal falconBOT
lethal elbow
short hazel
#

Not that either

#

Store your rotation in variables

#

private float pitch; for example

#

Add input to that, clamp, build a vector or quaternion from that and write it to euler angles

lethal elbow
#

Oh did you mean the actual rotation process? I thought you meant the object's current rotation

short hazel
#

None of your code processes a "location" (=position), everyhting is a rotation

lethal elbow
#

Yeah sorry, I was rushing. I changed it up

short hazel
#

I don't understand your question

lethal elbow
#

I'm not sure if you want the angle of the object or the rotating itself (transform.rotate etc)

short hazel
#

Full angles are stored, not deltas (changes in rotation). Deltas are added to the full angles variables

#

pitch would contain the accumulation of all changes in rotation you've made by moving the mouse around

upper forge
#

So im using a box colider2D to trigger a dialogue box, but when i go over it the first time it works but the i have to enter the collider 2 times before it triggers again....

any ideas why this would be happening?

short hazel
lethal elbow
#
 transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);

this is what I use to rotate the object, I should store this in Pitch?

short hazel
#

This rotates by an amount, so it is not correct if you need to use a variable containing a full angle

lethal elbow
#

I think getting the initial angle is where I am having the issue then

short hazel
#

You don't get the initial angle from anywhere. You set it to 0 in the code directly

#

private float pitch = 0; (individual variables) - or - private Vector3 rotation = Vector3.zero; (all-in-one)

rich adder
lethal elbow
short hazel
#

No, for the 3rd (? - I stopped counting) time, I said that we do not read the rotation from anywhere

wintry quarry
lethal elbow
#

I understand it now, This value (not linked to anything) will increase/decrease in proportion to the increment/decrement done by the transform.rotate

short hazel
#

By your mouse input*

#

Add mouse input to local rotation variable, clamp that

#

Write to object's location last. transform.localRotation = Quaternion.Euler(localRotationVariable)

#

Once! Do not use transform.Rotate() before or after since it'll overwrite/get overwritten by the one you just did

upper forge
#

Nothing is on the Sign Parent, does this help @rich adder

lethal elbow
#

Also thank you for being patient with me, I should have gone bed a while ago so my brain isn't braining

upper forge
lethal elbow
#
    currentMousePosition = Input.mousePosition.y;
                mouseMovement = currentMousePosition - startMousePosition;
                

                transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
                
                startMousePosition = currentMousePosition;


              
                pitch = Mathf.Clamp(mouseMovement, -3000f, 3000f);
                transform.localRotation = quaternion.Euler(pitch);

This is what I have so far but i'm clearly not thinking when tired so I'm going to sleep. I will come back to it tomorrow. Thanks to the people who was patient and tried helping me out

rich adder
lone barn
#

My project works fine in the editor but no script load when doing a quick local build.

A scripted object (probably xyz) has a different serialization layout when loading.
After doing some research, this could be linked to using conditional compilation in script but this project is brand new and I don't use such directive in my code. Second problem could be my asmdef but I've enabled Any Platforms and restarted my editor.
I don't know what to debug next. Could someone help?

oak kelp
#

when i make a new C# Script some of the code in my Player Scrpit stops working like [SerializeField] and stuff and for some reason i cannot use

player = GetComponentInParent<player>();
polar acorn
teal viper
oak kelp
polar acorn
oak kelp
polar acorn
#

So then what is the actual problem

teal viper
#

Can you be a bit more specific?

#

Does your computer shut down and your whole city gets a blackout or something??

oak kelp
#

the second i made the PlayerAnimEvents script everything in Player Script just stopped working and wont let me compile

teal viper
oak kelp
#

yes and its from this code is what the error says

void Start()
{
    player = GetComponentInParent<player>();
}
teal viper
#

Share the actual error. You should have done it at the very start.

oak kelp
#

Assets\PlayerAnimEvents.cs(13,39): error CS0246: The type or namespace name 'player' could not be found (are you missing a using directive or an assembly reference?)

#

the thing is i have player in the same script

teal viper
polar acorn
eternal falconBOT
upper forge
oak kelp
polar acorn
oak kelp
polar acorn
#

like what you're trying to get from GetComponent

oak kelp
#

i have Player

#

in the GetComponentInParent

#

with a cap P

polar acorn
oak kelp
#

oh my bad i sent that testing to see if lower would work

#

when i type GetComponentInParent it doesnt show like its not a known in VS

oak kelp
#

idk what i did but i fixed it but got a new error

#
MissingComponentException: There is no 'Rigidbody2D' attached to the "Platform (2)" game object, but a script is trying to access it.
You probably need to add a Rigidbody2D to the game object "Platform (2)". Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody2D.get_velocity () (at <cba4ac0113cf44c9935a337fd866f6c7>:0)
Player.Movement () (at Assets/Player.cs:112)
Player.Update () (at Assets/Player.cs:50)


#

nvm

#

i fix

#

thx for the help guys

polar acorn
oak kelp
#

i put the Player Script in the Platform(2) i didnt mean to

crimson whale
#

Having an issue with structure placement. One of the structures works perfectly fine, while the other constantly flies towards the camera, even though the code only adjusts the Y values.

Been troubleshooting this and can't seem to narrow down the issue, the code is attached. It froze at the end because I placed it.

Also lag is due in part to game running in background.

#

Found the issue, the raycast was hitting the cube. Not sure why the same wasn't happening with the cannon though, but after deciding to try a new layer anyways, it worked.

toxic frigate
#

hello, does anyone know why this happens? i thought i checked for missing teamControllers

#

the first screenshot was bad actually hold on

wintry quarry
toxic frigate
#

i have it continue if the object is null though

#

does it not work like that

wintry quarry
#

You're doing ship.transform

#

You can't do that if it's destroyed

#

You would need ship == null as the first condition

#

You're doing it after the dangerous stuff

stable quail
# toxic frigate

The order of the or statements in the if code matters as they are processed left to right

toxic frigate
#

ohhhhh

#

i see

#

okay, thank you

waxen adder
#

Is there a limit to the amount of corners that can be generated from NavMesh.CalculatePath?

#

Hmmm. Probably not. Going to elaborate further in a second

#

So here's my problem:

Blue filled in square at top left is destination. There is a blue wireframe cube at the bottom right that is the beginning.

The gray spheres are nav mesh corners. The blue wireframe cubes are the nav mesh corners being translated into grid nodes.

Strangely, my issue isn't with the wireframe cubes, but the spheres. As you can see, they kind of, give up before the end destination. These are nav mesh corners. And I have no idea why they're just... giving up before the end destination.

primal flare
#

https://youtu.be/Xf2eDfLxcB8?si=e5ShyBqMwqMahRtZ
i was watching this and did this but it dosent seem to work can anyone help me?

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

public class PlayerJump : MonoBehaviour
{

   [SerializeField] private ImputActionProperty jumpButton;
   [SerializeField] private float JumpHeight = 3f;
   [SerializeField] private CharacterController cc;
   [SerializeField] private LayerMask groundLayers;

   private float gravity = Physics.gravity.y;
   private Vector3 movement;

   private void Update() {
    bool _isGrounded = IsGrounded();

    if(jumpButton.action.WasPressedThisFrame() && _isGrounded){
        Jump();
    }

    movement.y += gravity * Time.deltaTime;

    cc.Move(movement * Time.deltaTime)
   }

private void Jump() {
movement.y = Mathf.Sqrt(JumpHeight * -3.0f * gravity)
}

   private bool IsGrounded() {
    return Physics.CheckSphere.(transform.position, 0.2f, groundLayers);
   }

}

Learn how to JUMP in VR using Unity's XR Interaction Toolkit. In this video, we create a new script for our Player and implement a jumping mechanic for our player using Unity's Character Controller!

Previous video: https://youtu.be/mYhVNtRGAhw

Get the source code: https://www.patreon.com/posts/unity-vr-source-88131424

// JOIN THE COMMUNITY DI...

▶ Play video
wintry quarry
#

Double check your code for typos and misspellings

north kiln
#

!ide

eternal falconBOT
near wadi
primal flare
#

ookk

#

@near wadi i got this from this web https://paste.ofcode.org/g9NRYjQwrKs6CFEn4F5V6V and it still dosent work idk if it fixes it for you or how it works i am very new to unity codeing

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

public class PlayerJump : MonoBehaviour
{

   [SerializeField] private ImputActionProperty jumpButton;
   [SerializeField] private float JumpHeight = 3f;
   [SerializeField] private CharacterController cc;
   [SerializeField] private LayerMask groundLayers;

   private float gravity = Physics.gravity.y;
   private Vector3 movement;

   private void Update() {
    bool _isGrounded = IsGrounded();

    if(jumpButton.action.WasPressedThisFrame() && _isGrounded){
        Jump();
    }

    movement.y += gravity * Time.deltaTime;

    cc.Move(movement * Time.deltaTime)
   }

private void Jump() {
movement.y = Mathf.Sqrt(JumpHeight * -3.0f * gravity)
}

   private bool IsGrounded() {
    return Physics.CheckSphere.(transform.position, 0.2f, groundLayers);
   }

}

eager spindle
#

please understand what you're trying to code rather than copypasting stuff from the web

primal flare
#

still dosent work

eager spindle
#

chatgpt doesn't work in 2024

wintry quarry
#

You ignored all the advice from above

eager spindle
#

generative AI has shat itself so hard it's now unuseable

primal flare
eager spindle
#

please understand what you're typing

#

don't copy paste from videos either

#

ok so what are you trying to do

primal flare
#

im trying to make a jump system for vr players

wintry quarry
#

If they had copied and pasted there wouldn't be such blatant errors

#

Configure your IDE as mentioned above and fix your typos

eager spindle
#

Integrated development environment.
It's the app you use to type your code.

Visual Studio and IntelliJ are examples of this

#

You may be prompted to install Visual Studio when installing unity

primal flare
#

i use vis stuido

rich adder
eager spindle
primal flare
#

no 2

#

what

#

ok

#

sryu

primal flare
#

bro what am i sopse to dooo

rich adder
primal flare
rich adder
#

to being configured

#

also you did not show the IDE

primal flare
#

what thats what it told me to do

rich adder
#

show me where

primal flare
rich adder
primal flare
#

i couldent find

rich adder
#

Microsoft Visual Studio 2022

primal flare
#

ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

polar loom
#

My visual studio won’t open… anyone know why?

teal viper
polar loom
#

I’ve tried double clicking the script in my unity, doesn’t work, I’ve tried opening it through my home, doesn’t work

polar loom
#

Sadly no cause I’ve had no time, do you think that’ll fix it?

spare mountain
polar loom
#

Ight

#

Yea cause I’ve had it before unity

spare mountain
polar loom
#

And when I got unity that’s when it started buggin

polar loom
#

Yea

spare mountain
polar loom
#

I’ve thought of it… but no

lone barn
teal viper
lone barn
#

The error details are the one in the devbuild log, this is the only info I have with the freezing build (which is normal if no script are compiled)

teal viper
#

Does it work if you take NetworkManagerUI out of the Project namespace?

polar loom
#

Hello

teal viper
polar loom
#

Could someone teach me how to make a teleport script when clicked with handtag?

lone barn
#

And the controller script works fine

teal viper
#

Also, do you reference that script anywhere?

lone barn
lone barn
#

what the hell, I've just added the script back and built again and everything works perfectly. i've banged my head for 2h yesterday on this

keen trout
#

helloo friends im getting following error while pushing my changes to remote repo

remote: error: Trace: ad2bd1b3597d974fd51d57b7eba80e30835602055d1b319384538a043f7c1883
remote: error: See https://gh.io/lfs for more information.
remote: error: File Library/PlayerDataCache/Win64/Data/sharedassets1.assets.resS is 157.50 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File Library/PackageCache/com.unity.burst@1.8.16/.Runtime/libburst-llvm-16.dylib is 124.60 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To github.com:Bloom56/Orbit-Runner.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'github.com:Bloom56/Orbit-Runner.git'

Please help me resolve it

#

How do i exclude this library file

#

i think unity is generating it automaticaly

lone barn
#

You should put /Library/ in your .gitignore

keen trout
#

where should I put it gitignore is big file

#

with lot of content

north kiln
#

!vcs

eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

north kiln
#

Your gitignore doesn't have the standard Unity stuff in it (like /[Ll]ibrary/), and committing those files is not only unnecessary, but also unreasonable

keen trout
#

the problems is i have made some changes in project that are also not getting commited

#

should I add /[Ll]ibrary/) this in gitignore

north kiln
#

You should be adding everything from the gitignore linked above to your .gitignore

#

Unless you've added something custom, your gitignore should 1:1 be that file

queen adder
#

Can i move ui components with code?

keen trout
#

im still facing same problem

#

even after changing gitignore

spice lion
#

can someone help me with this

queen adder
#

I can try

#

Whats wrong

spice lion
queen adder
#

And the code?

spice lion
#

coz its long

queen adder
#

So what i can tell you are trying to destroy an object

#

And unity is stopping you becouse

spice lion
#

why tho

queen adder
#

You are trying to do it kn edit mode

#

As it says in the code

spice lion
#

do i build it and run ?

queen adder
#

Error

spice lion
#

coz im making an apk

queen adder
#

Well what are you destroying?

spice lion
#

yes im messing with the game

queen adder
#

I think unity is trying to tell you that when you destroy them there will be no way to call it back

queen adder
#

Yeah

spice lion
#

what if i use build and run

queen adder
#

You cant build when there is an error

#

Im pretty sure

#

Try making it a prefab

spice lion
near wadi
#

when i reference a GameObject, is has to come from Hierarcy, right? i would not be able to use the 'parent' prefab from the Project

eternal needle
spice lion
eternal needle
eternal needle
near wadi
spice lion
#

not rlly

eternal needle
# spice lion not rlly

then you should read the error and reconsider what your code is doing. your code is trying to destroy something in edit mode when you say you dont want to

keen dew
#

Is that a script that you wrote or from an asset?

spice lion
keen dew
#

Got it from a game as in ripped it?

spice lion
keen dew
#

We can't help with that, even if you have permission

spice lion
strange cape
keen dew
#

Your movement code in FixedUpdate overrides horizontal velocity

strange cape
#

how should I do it?

strange cape
ivory bobcat
#

+=

strange cape
#

did I write =?

#

FML

#

thanks alot

keen dew
#

Either use AddForce instead of setting velocity directly or don't set the velocity while dashing is happening

ivory bobcat
#

Reminder that you may need to remove the second argument

strange cape
#

what do you mean by that?

strange cape
#

it feels more natural

ivory bobcat
# strange cape what do you mean by that?
playerRB.linearVelocity += new Vector2(speed * horizontalInput * Time.deltaTime, 0f);```Edited. You'll need to rework some stuff as this'll make you accumulate horizontally velocity.
strange cape
#

why? dont I need to keep the upwards velocity?

opal zealot
#

Hmm, is there any context to solve this sort of issue?: Assets\MainGameProject\CharacterController\Scripts\PlayerLocomotionInput.cs(7,79): error CS0146: Circular base type dependency involving 'PlayerLocomotionInput' and 'PlayerLocomotionInput'
Following a video tutorial from here: https://youtu.be/muAzcpAg3lg?si=IptL5gCbyegydth6&t=799

But I changed the PlayerControls on my Input System to PlayerInputSystem for organizational reasons. Did I break something in turn?

Code link: https://hastebin.skyra.pw/cuqudodewe.csharp

In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topics like movement, jumping, slopes, wall handling, step handling, animation, blend trees, Mecanim, Cinemachine, avatar masks, animation layers and multiplayer.

This is a free complete course...

▶ Play video
astral falcon
scenic maple
#

no they aren't

#

well, maybe, but you wouldn't be able to see it in that screenshot

#

the screenshot shows a nested interface

#

the ide doesn't look set up, you have no diagnostics

#

the class already inherits from MonoBehaviour, you can't inherit from multiple classes

#

the error would be different

#

where is PlayerLocomotionInput.IPlayerLocomotionMapActions coming from? it doesn't exist in the code you linked

astral falcon
#

its an interface he tries to inherit from, but as he tries to get it from the class itself AND its not there, it wont work. thats why I suggested him to look for his source of code again. rhetorical question more or less

opal zealot
astral falcon
# opal zealot

But where is that interface you are trying to implement here?

#

you just changed it? D:

#

It says playercontrols in your screenshot

opal zealot
astral falcon
#

in your own code, it says PlayerLocomotionInput. Take care of what you are doing

opal zealot
#

Ok

astral falcon
#

Following a tutorial without thinking will leave you without any additional knowledge when finished

opal zealot
#

Ok

#

Head's up for an update:

#

Assets\MainGameProject\CharacterController\Scripts\PlayerLocomotionInput.cs(7,57): error CS0535: 'PlayerLocomotionInput' does not implement interface member 'PlayerInputSystem.IPlayerLocomotionMapActions.OnMovement(InputAction.CallbackContext)'

burnt vapor
#

If your !ide is properly configured you can call quick actions on the interface and implement it

eternal falconBOT
opal zealot
#

It doesn't automatically generate the Interface as far as I know of.

scenic maple
#

do what fusedqyou linked, presumably for vscode. your ide doesn't have diagnostics, you need to set it up

burnt vapor
#

Judging by the screenshot it looks configured, so I'm confused why you'd have an issue here

scenic maple
#

definitely not configured

burnt vapor
#

I don't know which one I am supposed to look at

scenic maple
#

that one's from the video

burnt vapor
#

The first one is not configured, the second one is

#

Then it's not configured

#

I'm surprised nobody mentions their ide must be configured then

opal zealot
burnt vapor
opal zealot
#

Its installed BTW

#

This might have something to do with it:
Cannot find .NET SDK installation from PATH environment. C# DevKit extension would not work without a proper installation of the .NET SDK accessible through PATH environment. Rebooting might be necessary in some cases. Check the PATH environment logged in the C# DevKit logging window. In some cases, it could be affected how VS code was started.

burnt vapor
#

Sorry, no idea.

#

VSCode is generally not the best solution when it comes to Unity development

scenic maple
#

works well for me

#

but i also use vscode for all my development

#

so i know how to deal with a lot of its quirks :p

rich adder
frozen plaza
#

is it possible to split a class into several files and have partial classes in them?

I tried but It's not possible to assign as a component anymore

rich adder
frozen plaza
# languid spire absolutely

How?

I had the class in one file and could assign it fine..
then I split it into 3 files and made them all partial class but I can't assign it anymore

frozen plaza
rich adder
#

ehh easier to manage smaller components than monolith even if its split into multiples

#

maybe you have initial friction but the benefit pays off ten fold

frozen plaza
# languid spire absolutely

I tried it with an empty monobehavior class and it actually works.. not sure why it doesn't with my actual class

languid spire
frozen plaza
languid spire
willow shoal
#

hi... why is it not working?

hexed terrace
#

!code

eternal falconBOT
willow shoal
#

ok

#

aaa

#

okey

hexed terrace
willow shoal
#
using System.Collections.Generic;
using System.Threading;
using Unity.VisualScripting;
using UnityEngine;

public class destroylll : MonoBehaviour
{
    public GameObject aaa;

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            Destroy (aaa);
        }
    }
}
rich adder
#

has this link ready you beat me to it UnityChanLOL

willow shoal
#

this script is not working

#

i add block for "aaa"

rich adder
languid spire
willow shoal
#

👍

rich adder
#

always describe , what is supposed to happen vs whats happening instead

#

along w showing the setup ofc

burnt vapor
#

Won't fix your issue, but get used to this habit ASAP

#

I suggest you start by looking if the method is being called with a log message. If not, follow the steps from the site that was linked.

willow shoal
#

thanks

#

i will try

willow shoal
#

thanks

rich adder
vernal spear
#

Hi folk, I have a technical question. why is SetActive so expensive? GameObject.SetActive() 2x in a single frame just consumes 0.3% CPU

#

is there a way to minimize it's usage?

#

I just want to stop it's ticks etc, so I can actually stop it's ticks manually and teleport it far away

#

I guess it's going to be more effective?

vernal spear
#

I'm using an object pool to minimize the effort of spawning an object, but enabling/disabling is not cheap as well as I see?

past leaf
#

Line 83 should be RemoveListener right?I'm not sure...
*A official sample(fps microgame)

past leaf
burnt vapor
#

Because if you don't, then the reference will persist and call the listener each time it is invoked

past leaf
#

Ok great,so that official got a mistake i think...

vernal spear
rich adder
#

what you're doing when those are active is more important to look at

cosmic dagger
# vernal spear is there a way to minimize it's usage?

Activating a GameObject calls OnEnable for each MonoBehaviour and continues to run their Update method(s). You can enable/disable specific scripts to start/stop their code from running, but you need to compare that performance to deactivating the GameObject . . .

night raptor
vernal spear
#

I guess its the CPU Usage, no?

languid spire
#

and that would be the cpu usage allocated to this process, not of your complete cumputer

inland kettle
#

I can’t get the screenshot cause of how fast the code runs, but mostly the collisions are detected up to a certain point, when the console doesn’t print the right tag anymore as shown in the video

#

Sorry for the late response

slender nymph
#

lmao "late", that was 5 days ago my guy. you can still screenshot it to show what happens even if the console is printing things quickly

inland kettle
#

5 days is a stretch

slender nymph
#

2 days whatever

slender nymph
#

right click it. also not a code question

night raptor
opal zealot
night raptor
#

@vernal spear regardless what you showed sounds quite much. It would require seeing the code and more of the profiler view to make sure you are not misinterpreting something or doing something in the code that makes it slow other than the SetActive call

inland kettle
#

after hitting the top wall it stops registering collisions in the console, ie works until 5th picture

slender nymph
#

screenshot the console window

stuck palm
#

why am i getting unassigned reference exceptions? its literally assigned there.

slender nymph
#

you have an instance of that component in the scene with that variable unassigned

vernal spear
inland kettle
#

paddle is wall player is paddle

wintry quarry
wintry quarry
#

It's working fine I think

slender nymph
# inland kettle

so as i guessed 2 days ago when this issue initially started, your console is set to collapse so you aren't seeing the subsequent correct collisions

inland kettle
#

ohh yea thanks

inland kettle
slender nymph
#

so now you need to look at your code and debug the values you use to see why it behaves the way it is

inland kettle
#

reflection doesn't work though

inland kettle
#

using my initial code or with reflect?

slender nymph
#

the current code that uses Vector2.Reflect

#

use the log message I gave you as an example of how you can print multiple pieces of data in one log and print all of the relevant values to ensure they are what you expect them to be

inland kettle
#

okay thanks

#

uhh what values should I be caring about

slender nymph
#

look at your code to find out

stuck palm
#

wow horrible screenshot

#

but you get the idea

inland kettle
slender nymph
#

print the values where you are going to use them. there's no sense in printing them in other methods, you need to know what they are at the time you use them so you understand what is happening

inland kettle
#

this is what I did

#

I printed the values and it printed wrong values

#

not what I expected

slender nymph
#

that's not helpful because you don't see the inputs you use. you aren't seeing the normal or the velocity before you assign it

stuck palm
#

recently learnt this lovely little operator

#

nice fallback if i ever forgot to set something in the inspector

languid spire
#

except it does not work with unity objects and should not be used with them

stuck palm
#

does it not?

#

how come

languid spire
#

would I say it didn't if I didn't mean it?

stuck palm
#

why doesnt it work

slender nymph
#

no, unity has overridden the == operator to handle destroyed objects when comparing to null. but the null operators like the null coalescing you are using do not use the overridden operator, so if an object is destroyed it will be == to null but not actually null

willow shoal
#

hi... how to make a block is visible after touching a block? "correctly and its working" some link or script? for this. im beginner

languid spire
#

because Unity handles null references differently than standard c# for it's objects

willow shoal
#

i need it notlikethis

stuck palm
#

i guess thats what this means then

slender nymph
#

yes

stuck palm
#

apparently you can't override the null coalesce operator

#

i wonder why

willow shoal
#

and what next?

slender nymph
# stuck palm apparently you can't override the null coalesce operator

correct, the null operators all do pure null checks. there's not typically a reason to override how null checks work, but since unity objects are created on the c++ side of the engine and can be "destroyed" there needs to be a way to represent that on the c# side which unity decided to make == null represent that

willow shoal
#
  if (other.CompareTag("Player"))
    ```
slender nymph
willow shoal
#

i found somethink

#
using System.Collections.Generic;
using System.Collections;
using Unity.VisualScripting;
public class turnon : MonoBehaviour
{
    public GameObject Player;
    void OnTriggerEnter(Collider Enemy)
    {
        if (Enemy.tag == "Player")
        {
            Player.gameObject.SetActive(true);
        }
    }
}```
#

its not working

polar acorn
willow shoal
#

okey

#

i will try

rocky canyon
#

too much info to fit in a good size constraint lol

polar acorn
rocky canyon
#
  • u probably got a copy pasta template
languid spire
low wasp
#

Hey yo! I hope everyone is doing well this fine Monday. I was wondering if someone can point out my mistake? I am trying to clone Pong. I am trying to add sound and SFX. I have been able to get the backgorund music working and the sound when someone scores. What I am missing is getting the bounce sound to play when the ball bounces off of the players and the edge of the screen. I have tagged them all on layer 7. I have tried to copy the code that makes the score sound work. I am just not getting it to work. Would anyone be able to point me in the right direction?

polar acorn
#

Unless you're mixing 2D/3D physics, in which case, stop

low wasp
#

LOL, I am not trying to mix them. I tried the to copy the top one, but it did not work either.

low wasp
frozen plaza
#

let's say I have a rectangle with 4 triangles. I assign the second triangles as the first submesh and the third triangle as the second submesh.. what happens to the indexes?

seems to me they're getting jumbled?! is it [1, 2, 3, 4] -> [2,3,1,4]?! (always + the 2 following ofc)

teal viper
frozen plaza
#

a rectangle with 4 triangles

teal viper
#

Ah, so it's not the vertex indices.

frozen plaza
#

yes, it is

#

its 12 indexes for the 3 triangles but for brevity i cut it down / 3

teal viper
#

Then I don't understand what you're trying to say or ask.

frozen plaza
#

I want to know how the indexes of the triangles get reassigned in mesh.triangles when I assign the submesh

teal viper
#

Assuming you want a quad out of 4 triangles(with a vertex in the middle), you'd have something like 012 023 034 041 assuming 0 is the one in the middle. And I don't think submeshes are relevant to that at all🤔

queen adder
#

Hey im making a point system and the question is how can i move the ui component along the canvas?

#

uning the set ofc

frozen plaza
#

hm.. I realize my question is wrong..

when I assign a material to that submesh.. what are the indexes for the vertices or triangles in that submesh (for the material or rather the shader)

teal viper
frozen plaza
#

and the triangles I pass in get reindexed from 0 then I guess?

teal viper
#

Should be, yes.

teal viper
frozen plaza
#

yea.. been testing out for a while now :>

#

but I always used .triangles

#

gonna try using .GetTriangles(submeshIndex)

low wasp
rocky canyon
#

very matrix'y

low wasp
rocky canyon
#

ohh.. that ruins it a bit 😛

low wasp
#

Maybe you can tell me what I am doing wrong again or point me in the correct direction. If I add the if statement for a layer 7 collision it works when the game objects are checked at triggers. The problem this makes the ball pass right through and not bounce off. If I remove the is trigger check box. The ball bounces but the sound does not play. How do I get both to work? I have even tried to do a separated at the bottom but it does not work at all.

eternal falconBOT
slender nymph
polar acorn
tribal pelican
#

i cant seem to get the unity syntax extension working in visual studio

low wasp
low wasp
toxic frigate
toxic frigate
#

pasting it here in case it was because of a dumb mistake because i can't figure out anything wrong with it

slender nymph
tribal pelican
rich adder
eternal falconBOT
rich adder
#

you installed the Unity workload you mean?

tribal pelican
rich adder
#

click the guides above

tribal pelican
#

thanks

rich adder
#

make sure you do each steps

#

regen project files after the steps, it will refresh it
(you will see the button for later use in one of the steps)

tribal pelican
#

its fine if i use vscode right? i was gonna use vs since thats what it defaulted to but if i can stay on vscode id like to

rich adder
#

as long as you configure them properly

tribal pelican
#

okay, thanks!

toxic frigate
# slender nymph be more specific than "isn't working"

in the code it is supposed to reject missiles tagged as "MissileTeamTwo" if the bool ScanForMissileTeamOne is set to true, and vice versa, however it still adds targets tagged as "MissileTeamTwo" if its scanning for missileteamone

slender nymph
#

well for starters you should be using the CompareTag method to check an object's tag rather than .tag ==. second, what debugging have you actually done?

tribal pelican
toxic frigate
#

i sprinkled debug logs in every if function in the IsTargetValid function, however they said that it was scanning correctly (if ScanForMissileTeamOne is true and the missile was tagged as MissileTeamOne it printed a log to the console) however it also said that it was ONLY seeing missiles tagged as MissileTeamTwo

tribal pelican
#

like, it doesnt recognize unity's syntax

slender nymph
tribal pelican
#

how do i do that

slender nymph
#

go through the guide and complete every step. you'll see the button if you actually do that

tribal pelican
#

i have done every step

#

there is no button

slender nymph
#

then you did not complete every step

tribal pelican
#

oh

#

im just blind

#

nvm

slender nymph
#

restart visual studio after doing so

tribal pelican
#

okay, i did and theres no difference

#

it does spit out errors tho

slender nymph
#

if it is still not working then screenshot three things and show them here: 1. your external tools settings. 2. the vs editor package. 3. the entire visual studio window with the solution explorer visible

tribal pelican
slender nymph
tribal pelican
#

i did tho?

short hazel
#

This is VS Code btw, make sure you selected the correct link

tribal pelican
rich adder
#

vscode requires this to work properly with unity

tribal pelican
#

and how am i supposed to know that if its not written on the one page meant to explain how to use it

#

it says "Installing the Unity extension installs all its dependencies required to write C# with Visual Studio Code, including the C# Dev Kit." but apparently not

#

(this is also in the vscode output btw)

The command could not be loaded, possibly because:
  * You intended to execute a .NET application:
      The application 'restore' does not exist.
  * You intended to execute a .NET SDK command:
      No .NET SDKs were found.

Download a .NET SDK:
https://aka.ms/dotnet/download


Learn about SDK resolution:
https://aka.ms/dotnet/sdk-not-found
rich adder
#

and I agree its an oversight on their part but its something we must live with

tribal pelican
#

so how do i do this?

rich adder
#

VS does the same shit except it installs it for you

rich adder
#

make sure its the SDK not the runtime

#

restart PC after install. if it asks to modify path make sure you check off YES

tribal pelican
#

idk last time i tried to manually install an SDK it was hell to find where i was supposed to put it

tribal pelican
wispy plover
#

Hello, do you know if i can simplify this animator ?

rich adder
#

also not a code question

wispy plover
#

what is this

rich adder
wispy plover
#

The chanel

wispy plover
tribal pelican
tribal pelican
#

okay

rich adder
#

can you screenshot your External Tools page in unity

tribal pelican
rich adder
# tribal pelican

try clicking Regen Project Files and double click script again, wait a few sec

tribal pelican
#

nope, still same error

rich adder
#

show the output

rich adder
tribal pelican
#

yup

rich adder
#

im trying to to google this error because I never seen it before tbh

tribal pelican
#

damn

#

why am i always cursed

rich adder
#

Ive set up VSCode so many times this is some new shte lol

#

try maybe installing an older version of .NET SDK maybe

rich adder
tribal pelican
#

.NET 8.0

rich adder
#

8.0.8?

tribal pelican
#

yea

#

8.0.8, release date September 24, 2024

rich adder
tribal pelican
#

i have version 1.94.0, lemme check if thats the latest

rich adder
slender nymph
#

honestly, if you cannot get vs code configured then consider switching to visual studio. it's much better.

tribal pelican
rich adder
#

true

tribal pelican
rich adder
slender nymph
#

that goes over the entire process, including installation

tribal pelican
tribal pelican
slender nymph
#

you will be unlikely to have other issues because unlike vs code, visual studio doesn't require a lot of extra setup

rich adder
#

just make sure you got the Unity Workload for VS Installer

tribal pelican
#

oh okay

#

i'll try then

tribal pelican
rich adder
#

yea, the VSCode one is more raw and uses the dotnet command (usually can use this to make a new ,net app via command line)

rich adder
tribal pelican
#

can i disable the shitty autocomplete

slender nymph
#

do you mean intellicode? because if so, then yes. if you mean the regular intellisense, that is not recommended

tribal pelican
#

like, this

slender nymph
#

well that's not the auto complete, what's below it is. and that is intellicode.

tribal pelican
#

how do i remove/disable intellicode

#

okay lol

#

okay its all good!

#

thank you so much

gleaming kraken
toxic frigate
gleaming kraken
#

    private void Start()
    {
        StartCoroutine(SpawnEnemies());
    }

    private void FixedUpdate()
    {
        
    }

    IEnumerator SpawnEnemies()
    {
        yield return new WaitForSeconds(3);
        SpawnEnemy();
    }

    void SpawnEnemy()
    {
        StartCoroutine(SpawnEnemies());
    }```

is there any better way to start the couroutine right after it ends?
slender nymph
#

why not just use a while loop if you want to make it keep going?

slender nymph
gleaming kraken
tribal pelican
slender nymph
#

make sure it is set correctly in External Tools and regenerate project files

polar acorn
slender nymph
polar acorn
gleaming kraken
polar acorn
slender nymph
#

note i am referring to putting the loop inside the coroutine, not where you start the coroutine

toxic frigate
gleaming kraken
#

wait whaat

polar acorn
#

before any of these ifs

toxic frigate
#

👍

rich adder
polar acorn
toxic frigate
#

I agree

slender nymph
#

how have you confirmed that it is not

toxic frigate
#

what do you mean

slender nymph
#

well you claim that it is returning true, right? how have you confirmed that

polar acorn
toxic frigate
#

its executing a block of code that should only be ran if its true, i'm adding a debug log to that block

slender nymph
#

show the current code, including how you are verifying that it returns true when it should not

tribal pelican
slender nymph
#

no

tribal pelican
#

every time ive created a new script it broke and i needed to regenerate them for it to work again

slender nymph
#

how are you creating the scripts?

tribal pelican
#

going into the components, and crating a new script

slender nymph
#

just to confirm, you mean you are selecting the option to create a new component from the AddComponent menu in the inspector of a gameobject?

tribal pelican
#

yup

slender nymph
#

have you done something silly like disable unity's Auto Refresh?

tribal pelican
#

i havent touched that, so i doubt it?

slender nymph
#

humor me and check, it should be in the editor settings in preferences

lone sable
#

I have this strange issue. I'm trying to bounce a projectile off of a wall, however, sometimes, it bounces off at weird angles/ignores the Normal?.As shown in the screenshot. The green trail is the projectiles actual movement, the minor red line is the raycast debug. The actual code for getting the reflect is the following, please ignore the weird Utils/other things, I was attempting a few different solutions

The weird thing is, it looks to be getting the inside of the mesh, and not the outside of it, causing it to reflect downwards instead of off the wall like I'd expect.

RaycastHit[] hits = Physics.RaycastAll(transform.position - transform.forward, transform.forward);
        foreach (var hit in hits) {
            Debug.Log("Hit: " + hit.collider.gameObject.name);
            if (Utils.WillLayersCollide(gameObject.layer, hit.transform.gameObject.layer)) {
                Vector3 hitNormal = hit.normal;
                Debug.Log(hitNormal);
                Vector3 bounceDirection = Vector3.Reflect(rb.velocity, hitNormal);
                rb.velocity = bounceDirection;
                Debug.Log("Bouncing");
                return;
            }
        }
slender nymph
#

RaycastAll does not guarantee an order for the returned hit objects. is there a specific reason you are using RaycastAll for this and not just a regular Raycast to get just the first hit?

slender nymph
#

in the Asset Pipeline section

lone sable
tribal pelican
#

nope, its correctly enabled

slender nymph
#

the close visual studio and restart the unity editor. after that open the External Tools section and let me know if Visual Studio is still assigned as the external script editor.

tribal pelican
#

oke

slender nymph
slender nymph
#

okay then go ahead and try to see if it's working now

tribal pelican
#

it is working rn, lemme see if it still works if i create a new script

#

nope, doesnt work

#

creating a new script breaks it, and i do need to regenerate the project files

lone sable
gleaming kraken
lone sable
# slender nymph yeah so you should probably switch to the singlular Raycast method and you can p...

Still happening with the following.

RaycastHit hit;
        if (Physics.Raycast(transform.position - transform.forward, transform.forward, out hit, 10f, Utils.GetCollisionMatrixLayerMask(gameObject.layer))) {
            Vector3 hitNormal = hit.normal;
            Debug.Log(hit.collider.gameObject.name);
            Vector3 bounceDirection = Vector3.Reflect(rb.velocity, hitNormal);
            rb.velocity = bounceDirection;
            Debug.Log("Bouncing");
            return;
        }

Where the util is

public static LayerMask GetCollisionMatrixLayerMask(int layer) {
        LayerMask collisionMask = new LayerMask();

        for (int i = 0; i < 32; i++) {
            if (!Physics.GetIgnoreLayerCollision(layer, i)) {
                collisionMask |= (1 << i);
            }
        }

        return collisionMask;
    }
#

And for reference the collider on the wall is just a good ol cube.

ember tangle
#

I need two physics GameObjects to detect each other's collisions but not interact / apply force to each other. I'm currently trying every combination of collider and rigidbody to no avail. The game is 2d.

#

okay I fixed it, projectile is trigger now

deft grail
dense pier
#

hi all, I'm making my way through cs course for beginners, got stuck on setting axis frame for a cube guy. This is the error I get " Assets\Scripts\Player.cs(35,66): error CS1003: Syntax error, ',' expected " I tried to retrace my steps but nothing worked...what did I missed? ```public class Player : MonoBehaviour
{
public float speed = 3.5f;

void Start()
{
    transform.position = new Vector3(0, 0, 0);
}

void Update()
{
    float verticalInput = Input.GetAxis("Vertical");
    float horizontalInput = Input.GetAxis("Horizontal");

    transform.Translate(Vector3.down * verticalInput * speed * Time.deltaTime);

    transform.Translate(Vector3.left * horizontalInput * speed * Time.deltaTime);

    if (transform.position.y >= 0)
    {
        transform.position = new Vector3(transform.position.x, 0, 0);
    }
    else if (transform.position.y <= -3.8f)
    {
        transform.position. = new Vector3(transform.position.x, -3.8f, 0);
    }


    if (transform.position.x >= 11f)
    {
        transform.position = new Vector3(transform.position. -11f, y, 0);
    }
    else if (transform.position.x <= -11f)
    {
        transform.position = new Vector3(transform.position. 11f, x, 0);
    }

}

}```

versed cove
#

Does anyone know what might be the cause of this mouse jumping?

I have a player empty gameobject with a movement script on it and a character controller, then I have a body inside of that which is just a capsule with a collider, then a camera in the body.

float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);

cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
transform.Rotate(Vector3.up * mouseX);```
polar acorn
#

(You will almost certainly need to adjust your mouseSensitivity value after making this change, it'll be much faster)

versed cove
#

oh

#

lord

#

you dont say

dense pier
versed cove
#

that fixed it lol thanks

polar acorn
polar acorn
# versed cove that fixed it lol thanks

'round these parts we call it "The Brackeys Error" because he did it in an early video and everyone just copy-pastes his code for their tutorials and we're still dealing with it to this very day

versed cove
#

damn 😭

steep rose
# dense pier this is the one

you can do transform.position.x + 11f, x //this is the y float of a vector so i dont know why you have x here, 0 if you are looking for an offset. fixed it I got a little mixed up

versed cove
#

darn brackey

dense pier
steep rose
#

you need a ,

polar acorn
steep rose
#

also thats not valid code

polar acorn
#

transform.position.11f is not a thing

devout flume
steep rose
#

i have zero clue of what you want though

stiff ocean
#

transform.position.(x/y/z)

celest flax
#

Does anyone have an idea as to why the following code would give me a NullReferenceException for line 7?

2
3  void Start()
4  {
5      foreach(EnemyBrain enemy in FindObjectsOfType<EnemyBrain>())
6      {
7          enemyList.Add(enemy);
8      }
9  }```
wintry quarry
#

When you use the ., you need to make sure the thing on the left side of it isn't a null reference.

#

All references start out as null and will be null unless you assign them somehow. Either in the inspector or with the = operator

#

Your reference here is private, so the inspector is not an option. Therefore you have to assign it somewhere with the = operator

tepid frigate
#

If my object has a velocity, will its position be different between the Update and LateUpdate calls to a script?

wintry quarry
tepid frigate
#

Yeah the position/velocity of the rigidbody,

wintry quarry
#

Well it depends on a few things

#
  1. Do you have interpolation or extrapolation enabled on the body
#

I believe if you have interpolation on then yes the position may change between Update and LateUpdate

#

if you don't have interpolation on, then the Rigidbody position will only change during the physics simulation which is after FixedUpdate and before Update

tepid frigate
#

It seems I will want to use FixedUpdate instead of Update

wintry quarry
#

also note that Rigidbody.position and Transform.position can be different, especially with interpolation

wintry quarry
tepid frigate
#

Ok well my solution isn't working so well so here is what I am trying to do.
My characters are squares. Imagine square A and square B.
When A jumps on B, I want it so that when B moves, A also moves (like there is 100% friction).

I would use 100% friction except that would also mean when A moves, B also moves, which I dont want

#

I think the problem with FixedUpdate was that it didn't look smooth since it gets called less frequently than Update (sometimes)

wintry quarry
#

you want a platform

tepid frigate
#

wdym

wintry quarry
#

It sounds like you're taking about like having moving platforms for the character to jump on

tepid frigate
#

Like putting a platform on the characters head?

#

I will try that ig

wintry quarry
#

I'm asking a question

#

not making a suggestion

#

"a platform" doesn't really mean anything specific

bold plover
#

Any better than average state machine tutorials out there? Most of the ones I've been able to fine seem ghetto and have let me down.

tepid frigate
#

Its kind of like Pico Park mechanic, if you every played it

wintry quarry
tepid frigate
#

Like rn the characters can jump on each other, but since there is no friction, when the lower character moves, the upper character does not move with it

bold plover
#

Every day I learn there are a lot of tutorials out there that do more harm than good when you try to build on them. ;-;

toxic frigate
vocal quiver
#

Can someone explain why my muzzleflash is not aligned properly with the gun even though in the scene view, that doesnt seem to be the case

polar acorn
vocal quiver
simple falcon
#

crap'ola I copied pasted copy pasted saved and cant undo, got a funni format now

#

tried paste plain text and paste back in from notepad.exe already using UTF-8

#

I tried googling, sorry if this question is just plain odd

wintry quarry
simple falcon
#

thank you though

north oar
#

can someone send the tutorial thing on how to get code to autocomplete

eternal falconBOT
north oar
#

thx

#

I’ve done everything it said but it’s still not autocompleting my code

rich adder
north oar
#

oh it just started working

#

i swear it wasnt working like 10 seconds ago

rich adder
vocal urchin
#

I now know OnDestroy and OnDisable are not the same 🙂

primal turtle
#

What is UTF-8?

polar acorn
primal turtle
#

Thx

#

I don’t have access to a search engine currently and wanted to know.

acoustic sequoia
#

Hey everyone, I am wondering if someone can give me some keywords to search for or straight up links to something that will help me acheive the following:

I want to create code that will help me simulate millions of games of a "connect-4-like" game to find out either; what the next best move is by weight, or just simply giving me statistics on who is more likely to win just by playing first.. etc.

any help is greatly appreciated... except a link to a connect-4 neuralnetwork github lmao. I'm trying to apply knowledge to my own game... connect-4 just closely resembles it. thanks!

prime cobalt
#

Hey so I have this script for having an enemy turn to face the player via animations which turn it to face a specific angle. But when I want to to take its new angle into account when deciding how far to turn again it just wont work. When I have the current transform - rotation that faces the enemy it's a negative, and when I have the rotation towards the enemy - the current rotation than it gives me a completely different current rotation despite me not touching anything besides the transform.rotation.y - lookrot.y part.

wintry quarry
#

that's for chess not connect 4, but it should be applicable to any game.

wintry quarry
#

euler angles are not unique, as you are seeing

#

And there's no telling which of the many valid combinations of euler angles the Transform will give you back for any given rotation.

#

What are you trying to achieve exactly?

prime cobalt
#

I have this animation tree which turns a given amount of degrees. I'm trying to get the amount of degrees between the enemy's current rotation and the rotation which faces the enemy that need to be fed into this in order to turn.

#

I guess you could just contextualize it as getting the amount I would need to transform.Rotate between the current point and the one I need to face

wintry quarry
prime cobalt
#

Ok I'll try that out

tepid frigate
#

I want to be able to treat the characters as moving platforms.

Ok so I have it when character A jumps on character B, A.transform.parent becomes B.transform. Yet whenever B moves, A doesn't move. I have read it might be because I am using RigidBody2D with dynamic body type, but I have seen tutorials where it worked.

Is it because both A and B are dynamic, and B (the moving platform in this case), should be kinematic?

wintry quarry
#

Just playing with parenting and rigidbody body types won't get you the effect you need

acoustic sequoia
wintry quarry
frozen plaza
#

I got a quesiton about lifecycle..

my GameObject instance is seemingly reinstantiated on a domain reload but neither Awake nor OnEnabled fire.. do I really have to catch OnAfterDomainReload statically and then roll that over on the instances by hand?

#

or should I just do all my initialization in the ctor?

wintry quarry
#

What is this causing an issue with

frozen plaza
#

I got some variables that come up null after the domain reload and I want to have it consistent.. I would want to reload the parts that need reloading but I'm thinking now.. if the object is completely reinstantiated I best just initialize everything fresh in the ctor

wintry quarry
#

what kind of variables?

#

Static variables or something?

prime cobalt
thorn fiber
#

I'm using a raycast to determine LoS between non-player entities. I'm a bit lost on finding anything but the target's center. Is there a way to work out the profile of a hit entity? (from there I could ray cast the left-most point, right-most, etc and get everything I need).

wintry quarry
#

maybe like 4-5 representative points for example

thorn fiber
wintry quarry
#

that's not going to be incredibly accurate depending on the shape of the object though

thorn fiber
#

the accuracy isn't a huge concern, as long it's not heading into jank territory. The main issue I want to overcome is where a unit may be partially viable behind something (say, terrain) but the ray cast will intersect the obstruction when looking at the center.

#

The more I think about it, the more I think the empty objects is the go. They detect each other via colliders, so instead of firing 1 ray cast at the entity (defaulting to center), I can loop the empty objects until I see one.

#

Thank you!

frozen plaza
# wintry quarry what kind of variables?

ok, so I got a couple member variables and I would set all this up in the ctor but MonoBehaviour can't have a ctor

UnityException: GetComponentFastPath is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'DO_Planet' on game object 'Planet'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.Component.GetComponentFastPath (System.Type type, System.IntPtr oneFurtherThanResultValue) (at <91ab5f1018a44edcbcbbe289ed4303bc>:0)
UnityEngine.Component.GetComponent[T] () (at <91ab5f1018a44edcbcbbe289ed4303bc>:0)
DO_Planet..ctor () (at Assets/_Scripts/Planet/DO_Planet.cs:62)

so what's the best way to initialize lifecycle wise.. needs to be availble after domain reload. Start, Awake, OnEnable are not called

wintry quarry
wintry quarry
#

You can always just use a property

#

and lazy load it

#
private Planet _planet;

public Planet Planet {
  get {
    if (_planet == null) _planet = GetComponent<Planet>();

    return _planet;
  }
}```
frozen plaza
#

I want to do initialization logic on this object though and I need the components

wintry quarry
#

do the initialization logic lazily too

#

It's all just... very vague to me

frozen plaza
#

meh :|

wintry quarry
#

you're saying you need initialization logic and all this stuff - and it's for an editor tool or something

#

seems like fields on a MonoBehavuour might be the wrong tool for it

#

It's not clear why your values are being reset if they're normal serialized fields

#

that's not supposed to happen

#

so something weird is going on here

frozen plaza
#

I just want to make sure the object is ready when I call things on it from my editor tool.. it's weird to me the object is being reinstantiated but there is no lifecycle hook and I can't use the constructor

wintry quarry
#

have you editor tool call an Initialize function

#

My guess is you're using nonserialized fields or something

#

which yes, will go away on a domain reload.

frozen plaza
#

marking the fields as [SerializeField] helped but now my issue is, I serialize a dictionary by hand:

[SerializeField]
  private Dictionary<int, DO_Planet_Biome> _biomeTriangles;
//---
    string json = JsonUtility.ToJson(_biomeTriangles, true);

the dictionary is definitely not empty but the json comes out {}

any idea why?

wintry quarry
frozen plaza
burnt vapor
#

JsonUtility can't serialize/deserialize common types

#

But even then, Unity can't show your dictionary in the inspector; you probably need to create a custom editor for it

wintry quarry
#

or grab a serializable dictionary off the shelf

scenic maple
wintry quarry
scenic maple
#

stj is the best json serializer, so that's not true. can unity not include nuget packages?

wintry quarry
#

What makes it the "best" serializer in your opinion?
And no, Unity cannot use nuget packages out of the box

scenic maple
#

perf mostly

#

stj is a lot faster than anything else

wintry quarry
#

What are you basing that on?

scenic maple
#

like every source online. it's also fairly easy to benchmark yourself

#

but not really important if you can't use it anyway yep

wintry quarry
#

I can't find any source that compares Unity's JsonUtility with System Text Json

scenic maple
#

possibly because a comparison isn't easily possible

#

i would be very surprised if JsonUtility was anywhere near stj

wintry quarry
#

JsonUtility is pretty feature limited, and focused on speed

scenic maple
#

stj is made by the greatest minds at dotnet, it only makes sense that they know how to eek out every cpu cycle they can :p

wintry quarry
#

I wouldn't be surprised if it beats Newtonsoft

burnt vapor
scenic maple
#

yeah figured

#

unlucky

burnt vapor
#

And Newtonsoft has an easy to use library for Unity

frozen plaza
#

using newtonsoft now, thanks guys

dark comet
#

@wintry quarry So these are the two scripts:

Script 1: A Script designed to re-order bones of a SkinnedMeshRenderer to match another SkinnedMeshRenderer's bone order (using the root bone)

#

Script 2: A script that "Creates a new mesh based off the bone structure of a base mesh and ensures everything is in the correct order in the new mesh."

#

So my issue is that the second script works, but the results aren't as good as the first, as it does attach the new mesh to the bone order of whatever you are trying to mimmick, but does so with a lot of cavieats. One problem is that if the bone locations are even slightly off, the area where bones rotate around, will appear to be outside of the model, causing the rig to break. The first script is really good, looks the best, but does so by having a separate SkinnedMeshRenderer, and I want to end up with the ability to seamlesly switch the mesh in the SkinnedMeshRenderer without the bones breaking (if that makes any sense. Basically, combining the quality of the first script, with the end result of a seperate new mesh of the second.)

#

The second script does take into account the "bind pose" so I'm looking into that, but it's honestly so over my head all of this

sand condor
#

Is there a way to make this (a unity scene file) show up in editor?

public Scene _scene;

I basically want to link a scene to a background music file. I could use the build index ofc, but just curious how to make the field show up in my inspector. 🙂

burnt vapor
#

Unless this changed in the past few years. it didn't when I used it

sand condor
#

Asked chatGPT and it says its not possible

burnt vapor
#

You can always make a custom editor

night raptor
#

They are not. It's Run-time data structure as the documentation tells

burnt vapor
night raptor
#

You can find assets online for doing just that though

burnt vapor
#

I can't verify it (still) works. I suggest you try making your own from this reference

night raptor
#

It's shame the Scene assets are made so they cannot be easily referenced. I bet almost all larger Unity dev companies have made their own scene management tools to easily reference and manage their scenes

burnt vapor
#

I would not be surprised if there are readily available libraries that allow you to see Scenes and Dictionaries and all that in the inspector

#

Perhaps they haven't done it because it's opinionated, but it's not the only missing thing that you'd expect to just work

tulip nimbus
#

Why does this show an Error at Random? Before pasting in the Instantiate code above it worked just fine

lone sable
#

I posted about this yesterday with no real luck so I'm posting again this morning.

Im having this strange issue where when I'm trying to reflect projectiles off of a wall, they reflect off the inner portion of the collider, as seen in the photo. The green trail is the projectiles movement, the red debug raycast is the raycast seen below. I also checked the normal/hit position and debugged that, where it shows that it is inside of the collider at the normal you'd exepct to see in that photo. (Tho not the expected results.)

Any ideas?

RaycastHit hit;
        if (Physics.Raycast(transform.position - transform.forward, transform.forward, out hit, 10f, Utils.GetCollisionMatrixLayerMask(gameObject.layer))) {
            Vector3 hitNormal = hit.normal;
            Debug.Log(hit.collider.gameObject.name);
            Vector3 bounceDirection = Vector3.Reflect(rb.velocity, hitNormal);
            rb.velocity = bounceDirection;
            Debug.Log("Bouncing");
            return;
        }

Where the util is

public static LayerMask GetCollisionMatrixLayerMask(int layer) {
        LayerMask collisionMask = new LayerMask();

        for (int i = 0; i < 32; i++) {
            if (!Physics.GetIgnoreLayerCollision(layer, i)) {
                collisionMask |= (1 << i);
            }
        }

        return collisionMask;
    }
night raptor
tulip nimbus
#

Yeah thats it, since error messages seem so specific its hard to translate them correctly without misspelling a word since mine are in German. Does the Error code work too for the future?

north kiln
#

both preferred, even if german

tulip nimbus
#

I took out using System; would this break anything significant? Because it works now

north kiln
#

if you're not using it, then you don't need it

tulip nimbus
#

Thanks alot!

night valve
#

Sometimes you will need both namespaces, so you can specify which one to use by writing System.Random.Next() for example

burnt vapor
#

Or use a using statement like a sane person

using UnityRandom = UnityEngine.Random;

...

code
{
  _ = UnityRandom.Next();
}
night valve
#

What a smooth little trick! [noted]

gleaming kraken
#

this has been bugging me for a while, sometimes I try to reference anything inside Unity or System or any of the essentials, and vs 2022 acts as if it's not there. Restarting fixes it, but is there any other solution to this?

eternal falconBOT
wintry quarry
gleaming kraken
wintry quarry
#

Also make sure your IDE package in Unity is up to date

gleaming kraken
#

alright, will do. Thanks.

inland kettle
slender nymph
#

then re-read that message

inland kettle
#

how are the normal and velocity inputs?

slender nymph
#

because those are the values you input to Vector2.Reflect. i'm not saying they are input from the player

inland kettle
#

ohh ok

#

this okay?

slender nymph
#

now you should be able to see why the Vector2.Reflect is behaving the way it has been. then i get to link you to a message from 3 days ago that also explains it

inland kettle
#

reflecte vector isn't working right

opal zealot
#

Is there any context with these two errors?:


Assets\FoundationalRealm\PlayerCharacterController\Scripts\PlayerCharacterLocomotionInput.cs(7,66): error CS0535: 'PlayerCharacterLocomotionInput' does not implement interface member 'PlayerControls.IPlayerCharacterLocomotionMapActions.OnMovement(InputAction.CallbackContext)'```

Especially as I followed excatly as the video is setup for `IPlayerLocomotionMapActions` in this video: https://youtu.be/muAzcpAg3lg?si=M3Jfn-y6fCX-2zNe&t=766

```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace FoundationalRealm.PlayerCharacterController
{
    public class PlayerCharacterLocomotionInput : MonoBehaviour, PlayerControls.IPlayerCharacterLocomotionMapActions
    {

        public void OnMovement(InputAction.CallbackContext context)
        {
            throw new System.NotImplementedException();
        }
        // Start is called before the first frame update
        void Start()
        {
        
        }

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

}

In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topics like movement, jumping, slopes, wall handling, step handling, animation, blend trees, Mecanim, Cinemachine, avatar masks, animation layers and multiplayer.

This is a free complete course...

▶ Play video
slender nymph
inland kettle
#

...i mean yea

#

probably just dont understand it 💀

slender nymph
#

so which of the relevant values do you think is not what you expect it to be?

inland kettle
#

reflected velocity

slender nymph
eternal falconBOT
slender nymph
inland kettle
#

cause if it was reflected wouldnt the value just be the inputed velocity with one of the components multiplied by -1..

slender nymph
#

we obviously know that the reflected velocity is wrong. that is literally the entire fucking issue. you are trying to determine why it is wrong.

inland kettle
#

chill ok

opal zealot
slender nymph
# inland kettle chill ok

you've been at this for 3 days, and you've printed the relevant values but still somehow haven't noticed that your actual velocity before reflecting is practically 0. for the love of god think

slender nymph
opal zealot
#

Lemme check if I miss something

slender nymph
inland kettle
#

i thought the x and y were coordinates for the initial impact

opal zealot
#

Updating right now

slender nymph
opal zealot
#

Good news, I fixed the issue. Turns out I did miss a bunch of steps along the way. Thanks @slender nymph.

tender breach
ivory bobcat
tender breach
#

I did.

ivory bobcat
#

Where?

tender breach
#

I removed it

ivory bobcat
#

Log the tag of the other object before any evaluation and show us what the console printed

tender breach
#

IDK how to do that

ivory bobcat
#

How to log or how to show us the console prints?

tender breach
#

Both

frosty hound
ivory bobcat
#

For the first, just undo what you said you did here #💻┃code-beginner message
For the second, you would just screen capture the Unity console window

frosty hound
#

Oh wait, nevermind I recognize the account name.

#

Good luck lol. 🏃‍♂️

tulip nimbus
#

Everytime i tap on the screen a prefab "point" spawns for a few seconds to simulate touch on the mobile device, and then immediately destroys itself again.

Whenever another certain prefab is triggered by this point(by using collision), it is destroyed and i get added 1 point.

However i also want to make it so that when the background is accidently tapped, the console debugs: "FAILED" so i know it works and the player loses for missing the prefab.

This works, but whenever i tap the prefab, it both gives +1 point aswell as it debugs "FAILED" over and over again. As if it detects both the prefab and the background at the same time.
i tried changing the layer order but it still doesent work.

How can i make it in a 2D game, that a OnTriggerEnter2D of one object only applies to the next higher gameobject in a layer and not to those below it?

full owl
#
using UnityEngine;

public class spawner : MonoBehaviour
{
    public float maxTime = 1;
    public float timer = 0;
    public GameObject pipe;
    public float height;

    void Start()
    {
        GameObject newpipe = Instantiate(pipe);
        newpipe.transform.position = transform.position + new Vector3(0,Random.Range(-height,height),0);
    }

    void Update()
    {
        if (timer>maxTime){
            GameObject newpipe = Instantiate(pipe);
            newpipe.transform.position = transform.position + new Vector3(0, Random.Range(-height, height), 0);
            Debug.Log(newpipe.transform.position);
            Destroy(newpipe, 15);
            timer = 0;
        }
        timer += Time.deltaTime;
    }
}

``` Gues, I writing simple flappybird game. Why this code to spawn and moving pipe not wirking??
runic lance
tulip nimbus
polar acorn
runic lance
#

you probably can also use the MonoBehaviour event OnMouseDown

tulip nimbus
runic lance
#

pretty sure it reacts to mouse clicks and touches

tulip nimbus
#

Thanks alot!

polar acorn
# full owl I have this

As the game plays, do you see the timer variable increasing? Are you getting your log statements when a pipe is spawned?

low wasp
#

I have a question that I think I know the answer to. If I am creating games and I reuse my previous code for the new stuff. Is that wrong? I am thinking like player controllers, scoring systems, timers, and anything else that can get reused. My knee jerk answer is this is fine and kind of how it should be done. Don't reinvent the wheel every time. I can also see where this might be a crutch that holds you back from progressing in your skills. Thoughts?

slender nymph
#

there is no reason to reinvent the wheel every time you create a new project. reuse code when you can if it makes sense to