#💻┃code-beginner

1 messages · Page 133 of 1

north kiln
#

Oh, I would just cache the info from Update if I saw that

timber tide
#

yeah that's the work around

weak palm
#

oh interesting-- that wasn't the case for me but good to know jic! Thank you again!

vernal minnow
#

Alright, the bullet now shoots in the correct direction but is shooting from the same spot regardless of where the character is facing

#

The video is definitely helping me organize my code better aswell so thanks

timber tide
#

get the position and direction of the player and grab a position a unit or so ahead of their forward direction

vernal minnow
#

I believe it is pulling from its location, I think I may have modified it's spawn on accident

#

I'll review my code as I'm adding comments to see what's messing with it

timber tide
#

what you may be doing is getting an offset of the player position but in world coordinates

gritty lion
#

I need help with moving VisualElements programatically

#
    // Create the image on root
    _icon = new Image();
    panel.visualTree.Add(_icon);
     
    _icon.style.position = Position.Absolute;

    // Make it follow this visual element
     _icon.schedule.Execute(() =>
    {
        Vector2 direction = new Vector2(slotContainer.resolvedStyle.left - _icon.resolvedStyle.left, slotContainer.resolvedStyle.top - _icon.resolvedStyle.top).normalized;
        Vector2 newPosition = new Vector2(slotContainer.resolvedStyle.left, slotContainer.resolvedStyle.top) * direction * speed * (executionTime * 0.001f);
     
        _icon.style.left = newPosition.x;
        _icon.style.top = newPosition.y;
    }).Every(executionTime);
#

This is not working somehow

vernal minnow
gritty lion
#

All it does is stay on top left corner of the root

eternal falconBOT
timber tide
#

maybe the ide just telling ya that this code wont execute

summer stump
#

You are assumably looking at it when using the Editor? Not when built?

outer tree
#

anyone have an idea as to why the code isn't working? its c# and im trying to teach myself with some vids rn any help is appreciated 😁

timber tide
#

good starting point is to learn to print to console

#

in unity we use Debug.Log

#

it can print out of the contents of a variable as well as strings

wintry quarry
outer tree
#

so instead i would do something like

#

rb.ForceMode.Impulse(Vector3.up * 500);

#

would that work 🤔

ivory bobcat
outer tree
#

oops sorry i shouldve mentioned i found out the error

#

it was on line 14

#

RigidBody should've been Rigidbody

#

took me half an hour to find 😠

ivory bobcat
#
rb.AddForce(..., ForceMode.Impulse);```
polar acorn
eternal falconBOT
wintry quarry
robust condor
#

Can someone explain why you would call a delegate using an event instead of just running the functions subscribed to the event?

polar acorn
robust condor
#

So basically like an if check?

lethal kestrel
#

now i study both at university

north kiln
robust condor
#

I legit don't see a difference except the extra roundtrip:

using System;

public class EventRunner
{
    public event OnEventDelegate OnDelegateEvent;
    public delegate void OnEventDelegate(Object sender, EventArgs e);
    
    public event EventHandler OnNormalEvent;
    
    public void Run()
    {
        OnNormalEvent?.Invoke(null, EventArgs.Empty);
        OnDelegateEvent?.Invoke(null, EventArgs.Empty);
    }
}

public class Program
{
    public static void Main()
    {        
        EventRunner eventRunner = new EventRunner();
        
        eventRunner.OnNormalEvent += MyFuncNormalEvent;
        eventRunner.OnDelegateEvent += MyFuncDelegatEvent;
        
        eventRunner.Run();
    }
    
    public static void MyFuncDelegatEvent(System.Object sender, EventArgs e)
    {
        Console.WriteLine("RunDelegateFunction ran");
    }
    
    public static void MyFuncNormalEvent(System.Object sender, EventArgs e)
    {
        Console.WriteLine("MyFuncNormalEvent ran");
    }
}
north kiln
#

This is a dumb example

hazy delta
#

Hello, I've been following a YT tutorial on making a dialogue scene code. The code here has 0 issues and errors, but when played, does not show the output the code is supposed to give. Can anyone help pinpoint the mistake?

#

hold on wrong code

rich adder
hazy delta
rich adder
hazy delta
#

you're asking me to check the debug log right?

rich adder
#

which one

hazy delta
rich adder
hazy delta
slender nymph
#

!code

eternal falconBOT
hazy delta
# hazy delta

I'm actually thinking it might be this script that holds the problem bcs there are no colors on the FindObjectOfType code (which is a stupid reason probably, im still new)

north kiln
#

Your code looks very underhighlighted, are you getting proper autocomplete and error highlighting?

hazy delta
#

..i dont know, I dont understand how its not highlighted and just assumed its normal

north kiln
#

!ide it's not

eternal falconBOT
hazy delta
#

if i delete the FindObjectOfType, the rest of it gets highlited

#

so the problem is that?

hazy delta
north kiln
#

It says a number of other things also

rich adder
hazy delta
north kiln
#

If it says Miscellaneous Files, it's not configured properly

rich adder
hazy delta
#

what does that mean and what am i supposed to do to solve it?

gaunt ice
#

follow the bot message

rich adder
hazy delta
#

its...2019

rich adder
#

no

#

but you said you had the latest

#

which is not 2019

hazy delta
#

but it says its there are no updates needed

#

does that mean i have to delete and install the 2022 ver then?

rich adder
#

anyway updating is prob the least important step

#

there are more important ones prior

hazy delta
#

i see

slender nymph
rich adder
#

^ faster, better intellisense etc.

hazy delta
#

so what do i do with the misc thing?

#

i pressed it but it does nothing

slender nymph
slender nymph
#

was visual studio not listed in the options for the external script editor setting?

hazy delta
#

it was and i selected it already

slender nymph
#

then why are you attempting to follow the instructions for when it isn't listed in that settings menu?

hazy delta
#

i thought i was supposed to follow all of the instructions of all of the links

slender nymph
#

you are, but you should also apply some common sense. the instructions immediately before that are to select Visual Studio in a dropdown menu for the External Script Editor setting. this immediately follows it for if it isn't listed or you want to select a different/custom version of it. you do not need to do that part if you've selected the version you want to use already

north kiln
#

It does say Select one:
If VS is selected in the External Tools preferences then that part is done. Make sure VS has the Unity workload installed in the VS Installer and the VS Editor package is updated in Unity

hazy delta
#

oh..sorry

#

where is the VS editor package ?

north kiln
slender nymph
#

select the Unity Registry in the package manager if you do not see it listed in the In Project view

hazy delta
#

ah, i checked and its already installed and ✅

slender nymph
#

make sure to restart visual studio by closing it then double clicking a script from within your project after completing the guide to ensure that it reloads the project

slender nymph
#

does it still say Miscellaneous Files?

hazy delta
#

no

#

the code looks like this now, but it still doesnt make any changes in the game itself

tacit estuary
north kiln
#

there's also an error in this script underlined right there 🤔

tacit estuary
#

Also what is the underlined error?

hazy delta
#

FindObjectOfType

rich adder
#

prob deprecation nvm thats 2023 I think

hazy delta
#

its still not colored

rich adder
hazy delta
#

wait the underline is gone and the FindObjectOfType is colored now

#

i cant screenshot the hover description but it basically just says the code with a (+1overload) at the back

rich adder
#

its fine then

hazy delta
#

but the code still doesnt make any changes

rich adder
#

use the debugger and step through

hazy delta
#

yes

#

what is the debugger?

rich adder
#

put some breakpoints and check your variables

#

in vs is called Attach to Unity

#

prob one of the first tools you should learn

near wadi
#

Why does this work
transform.position = Vector3.zero;
But this does not?
transform.position = new Vector3.zero;

whole sapphire
whole sapphire
north kiln
north kiln
whole sapphire
whole sapphire
#

like i can't even run it

north kiln
#

Hover over it and read it

#

Vector2 is underlined

whole sapphire
#

'Vector2' is an ambiguous reference between 'UnityEngine.Vector2' and 'System.Numerics.Vector2'

near wadi
north kiln
#

Because Vector2 is a type, and you are creating a new instance of it

#

via its constructor

near wadi
#

Oh, i need to double verify that, that works

whole sapphire
north kiln
hazy delta
whole sapphire
#

use what le

near wadi
#

Thanks

north kiln
stuck mango
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformAttach : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Rigid")
        {
            other.transform.parent = transform;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Rigid")
        {
            other.transform.parent = null;
        }
    }


}

I've created this code to make player stay on my moving platform, i made it move by using animator with "Animate Physics" Everything seems okay till the platform starts moving. Meaning that i cant move on it, my ability to move my player comes back after it stops. Whys that?

hazy delta
#

the code still make 0 changes and it doesnt show me why

ivory bobcat
#

Are you getting any errors?

eternal needle
# stuck mango ```cs using System.Collections; using System.Collections.Generic; using UnityEng...

parenting for movement wont really be that good, and it seems your movement system is via the animator. Combining the animator with another movement system (a transform moving) isnt likely gonna work or have expected results. Not really sure what the physics part is for, the docs tell you what animatePhysics is for
https://docs.unity3d.com/ScriptReference/Animation-animatePhysics.html
How are you moving the player?

stuck mango
eternal needle
stuck mango
#

Yes.

hazy delta
#

i dont think so? im kind of confused on what to do

eternal needle
# stuck mango Yes.

the combination of MovePosition and having the parent also move might be causing weird results in that case then, can you show the movement code?

stuck mango
#

Yeah right

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

public class MovementScript : MonoBehaviour
{
    public float speed;
    private Rigidbody rb;

    public Transform orientation;

    float horizontalInput;
    float verticalInput;

    public Vector3 MinHeight;
    public Vector3 StartPoint;

    Vector3 moveDirection;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

    void Update()
    {
        MyInput();
    }

    private void FixedUpdate()
    {
        MovePlayer();
 
    }

    private void MyInput()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
    }
    private void MovePlayer()
    {
        moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

        rb.MovePosition(transform.position + moveDirection.normalized * Time.deltaTime * speed);
    }
}
#

very basic one

hazy delta
merry condor
#

hello there! I am just getting started on my game making journey and wanted to see if anyone has any tips on how to start learning code? i dont want to get stuck in youtube hell and just repeat tutorials

timber tide
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

timber tide
#

also make sure you know your c# before diving too far into unity

merry condor
#

thanks!

deep grove
#

i managed to do it but it's not exaclty at the edge of the screen

graceful citrus
deep grove
#

the arrow , it should point towards an objective at the edge of the screen , i folowed a tutorial for 2D and made it for 3D but i have that problem https://www.youtube.com/watch?v=dHzeHh-3bp4&list=LL&index=6

✅ Series Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53t6iznGWrD_QB66ZoIz2BHa
Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=dHzeHh-3bp4
Let's create a UI Arrow Pointer that will point to a location in our world.

If you have any questions post them in the comments and I'll do my best to answer them...

▶ Play video
#

and it's poinitng at me insead of the objective

#

i'm new to coding btw

deep grove
honest haven
#

whats the best way to set up a run animation uning get key. Im unsure if run should come from walk and can go back to walk if i let go of key down. is this the best way to set this up? if (Input.GetKey(KeyCode.LeftShift)) { currentState = PlayerState.Running; _animator.SetBool("isRunning", true); } else { currentState = PlayerState.Moving; _animator.SetBool("isMoving", true); }

languid spire
#

your code is not logical, the else condition will execute under ALL other circumstances

honest haven
#

yh whats the best way to go from walk to run

#

i mean i could check if current state is walk

languid spire
#

huh, change if you are walking and you want to run?

honest haven
#

is the logic on the animatior wrong?

languid spire
quick edge
#

Yo! Quick question. My maths are off here. I have three points A, B, C (Camera, Character, Target). I want my Camera to be exactly behind my Character while looking straight at the Target (I want a segment from A to C crossing B). How can I do that?

#

My idea was to take the direction from player to target, and then set the camera position as player "_player.transform.position - (distanceCameraPlayer * directionPlayerToTarget)"

#

But i'm not sure if it is correct

gaunt ice
#

your camera position is based on player.forward while its orientation based on its position and target, not sure what "behind" means

quick edge
#

I forgot to mention it's a FreeLook camera. Don't know if it can help

quick edge
gaunt ice
#

they are collinear

quick edge
#

Is this a question?

#

I want them to be colinear yes

gaunt ice
#

no, behind something usually mean -transform.forward, imagine the player looking up then if the camera is behind the player:
^
|
PT
C

#

back to your problem, you can construct a PT vector first, and P-some dist*PT can be the camera position
C<-- -PT*dist -----P----PT--->T

gaunt ice
#

yes

quick edge
#

Ok perfect! Thanks for the help!

gaunt ice
#

-vector is collinear while in opposite direction

#

btw normalize PT first

quick edge
#

Yes 👍

deep grove
quick edge
deep grove
vocal marlin
#

Hey, just wondering if there's any difference between this int(Mathf.Floor(entityHeight)) and this int(entityHeight) Ignore the variable names

quick edge
languid spire
deep grove
#

i sent a tutorail for it but it's in 2D

quick edge
#

Ok

vocal marlin
languid spire
quick edge
deep grove
#

np

split dragon
#

Hi. Although I am 99% confident in myself, I'd rather ask you: Using, which is indicated in gray, does this mean that it is not used in the script, and it can be safely deleted?

languid spire
#

yes

split dragon
#

Thanks

novel shoal
#

which topics should i study after the code beginner pathway?

languid spire
#

probably more information than you need but you should always remove unused using statements because although the script does not use them they do create a dependency in the compiled dll

woven arrow
#

Would make me really happy if someone could help me ^^

gaunt ice
#

why are you serialize the reference but not reference it directly in inspector?

languid spire
woven arrow
gaunt ice
#

didnt notice that, btw is your ide configured?

woven arrow
languid spire
#

what script?

oblique ginkgo
woven arrow
languid spire
#

so you need

SFXScript sfxScript = SFX.GetComponent<SFXScript>();
sfxScript.PlaySound("grinchDeath");
woven arrow
gaunt ice
#

the method is belong to your script not the gameobject

woven arrow
#

Ok, I think I know how to fix it now, thank you

dark hatch
#

probably zoomed out too much. press 'f' key with object selected

honest ingot
frozen pawn
#

Hi guys, I have two deferent custom classed lists and now i wanna check if they are equals or they are not, I do it like "If (list_1 == list_2)" and i don't get any error but they program always says they are not, even though their values are equal... any thoughts?

languid spire
frozen pawn
languid spire
#

by implementing your own compare method

frozen pawn
#

jeezz, I think i understand

#

is there any ez way to do it in like an hour ?

languid spire
#

Everything is easy, when you know what you you are doing, if you mean 'can I learn and implement this is an hour' then probably, no

#

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method for ordering or sorting its instances.

trail wharf
#

how to add the 3rd on screen stick, apart from left and right gamepad sticks, i am using android stick but somehow not working, what am i doing wrong?

ivory bobcat
frozen pawn
quick edge
#

Yo! In term of optimization, when should I look for it ? When my project is close to the end ?

charred fossil
#

Hi everyone, I am currently making a first person shooter and would love some help with an issue that I have encountered using Raycasting to "shoot" my player with my Enemy. It is not detecting that my player has the "Player" tag even when it does and I have no idea why. I would love some help as I am obviously new to Unity and I am so so stuck.

buoyant knot
#

middle to late, or when performance is so bad that something you did literally can’t work

ancient island
#

I think good practices during development will make your game optimized enough

buoyant knot
#

like, if you add a small feature that drops your FPS dramatically, you need to take care of that for that feature to be included

quick edge
#

Ok thanks! Is there Unity specific things that I should really be careful about ? (this is really vague I know)

rich adder
#

debugging should be first thing you learn

ancient island
charred fossil
eternal falconBOT
ancient island
charred fossil
#

It's the damagePlayer method on this paste of code

rich adder
#

gpt code

charred fossil
#

I've done that too but it hasn't helped

rich adder
#

exactly

languid spire
#

AI code, without a doubt

rich adder
#

also ur not printing hit.collider

languid spire
#

not even gonna read it

rich adder
#

so much wrong here

charred fossil
#

wait what no it's just the damagePlayer method that is AI because I was trying to fix it

rich adder
#

well it made it worse then

charred fossil
#

I just got the same error

#

wow sorry ig

rich adder
charred fossil
#

It's not an error it's just that the if statement for whether or not the gameObject that the Raycast collided with has the tag "Player" is never true and I don't understand why

valid pulsar
#

I am working on a script to print text into a box. I am trying to add something to change the text size as it prints and i want a bool in the that i can toggle to show or hide a graph with a line in it you can adjust that will be used to determine text size. I found this(https://stackoverflow.com/questions/72732460/unity-how-to-let-my-variables-show-up-in-the-inspector-if-a-boolean-is-true-an) which would work in a normal scenario but im storing all the data in a struct array so i can have different settings for different part of the sentence. I also need help getting a graph to show in the inspector because i cant find anything on that.

rich adder
charred fossil
languid spire
charred fossil
#

My problem wasn't AI generated that was just a couple lines that I took from AI because what I had before wasn't working at all. Wow kinda thought this discord was gonna be a bit more beginner friendly

languid spire
charred fossil
#

Why?

rich adder
#

we just know

charred fossil
#

It's for my A level computer science course work

languid spire
#

We see a lot of AI generated code, we have learned to recognise it

charred fossil
#

Well not very well obviously because it's not AI generated

#

I used a lot of Brackey's tutorials

#

and a few random ones from youtube

#

and a bit of just me trying to figure stuff out

ancient island
#

just because it has comments it doesn't mean its AI

timber tide
#

liar, no one actually writes comments

charred fossil
ancient island
rich adder
#

mate

#

// Function to kill the player
void Die()

#

no one writes comments like this

charred fossil
#

Yeah because I have to comment for my course work

#

wtf

#

I am supposed to comment everything

ancient island
#

I dont think an AI would comment this as "Bullet code"

#

lol

rich adder
#

alright forget this lol
I told you what you should do anyway, if you want to solve your issue learn to debug or go back to ai

charred fossil
timber tide
#

comments look legit just because you've plastered function everywhere and not method so ill give you that

charred fossil
#

I promise you the only thing AI is the damagePlayer function and that's just because I got so fed up with it not working I wanted to see if chatGPT could fix it

languid spire
charred fossil
#

Because once I've sorted it I delete it

#

I don't need to keep seeing that something is working

#

I only Debug.Log stuff that I am currently looking at

cosmic quail
charred fossil
#

Yeah I am doing that now. I am trying what @rich adder told me to do with the Draw line thing now

timber tide
#

debug your raycast without the layer mask and get that hitting anything, then use the layer mask and see if that's the problem

#

anything with a collider^

charred fossil
#

thank you

rich adder
#

Debug.DrawRay is the only sensible thing

cosmic quail
charred fossil
#

It's tagged with "Player"?

rich adder
#

layers are not tags

cosmic quail
charred fossil
#

My bad I'll do that now

#

That's the player one

cosmic quail
#

not Player

rich adder
#

oof

charred fossil
#

Yeah I know

cosmic quail
#

in the code you call it Player

charred fossil
#

just tried with whatIsPlayer and still no such luck

#

Yeah I mixed up referencing tags with Layers

#

I'll try by referencing the layer I really hope this works

bold nova
#

Why do I get this exception?

#

ArgumentException: JSON parse error: Invalid value.

#
public void SaveGameInfo()
{
    GameInfo dataTosafe = new GameInfo();
    dataTosafe.bestScore = this.bestScore;

    string jsonData = JsonUtility.ToJson(dataTosafe);

    File.WriteAllText(Application.persistentDataPath + "/savefile.json", jsonData);
    Debug.Log("Data saved");
}

private void LoadGameInfo()
{
    string path = Application.persistentDataPath + "/savefile.json";

    if(File.Exists(path))
    {
        GameInfo gameInfo = JsonUtility.FromJson<GameInfo>(path);

        this.bestScore = gameInfo.bestScore;
    }
}
#

GameInfo class only contains one int

short hazel
#

Your json text might be invalid or corrupted, post the contents of the file

#

Also for safety please concatenate file path with Path.Combine() instead of with +, it handles more cases and won't produce invalid paths

#

Path.Combine(Application.persistentDataPath, "savefile.json")

oblique ginkgo
#

uh no

#

the issue is

#

youre trying to parse json from the file path

#

not the contents of the file

#

but yes

#

use path.combine

rich adder
#

You need File.ReadAllText

#

then put that in FromJson

#
      var jsonData = File.ReadAllText(path);
             GameInfo gameInfo = JsonUtility.FromJson<GameInfo>(jsonData);```
bold nova
twin bison
#

Hi guys, I'm creating a brick breaker clone and I try to get into the observer pattern. What is the way to implement observer pattern when I have for example 50+ bricks? Do I have to subscribe to each of the bricks event? Or is there another way? Each brick has this script:

void OnCollisionEnter2D(Collision2D collisionInfo)
    {
        Destroy(gameObject);
        BrickDestroyedEvent?.Invoke();
    }

On my GameManager I subscribe to the prefab itself which does nothing, I think I have to find all of these and add a listener for each of them? It doesn't feel right to me

short hazel
#

Subscribe in the script that Instantiates the bricks if you're doing so by script

#

Or you can find all the bricks by script once, and loop over them to subscribe

twin bison
#

oh so in my BrickSpawner script i should get a reference to the GameManager and then subscribe like so?

twin bison
short hazel
#

The subscriber count doesn't matter, as there's only one receiver, the game manager

#

One brick out of 500 notifies the manager that it has been destroyed, not the inverse

#

The brick can pass itself to the event in case the manager needs to know which one raised the event: Destroyed?.Invoke(this)

twin bison
#

So for your first suggestion something like this might work?

private void SpawnBricks()
    {
        for (int i = 0; i < Rows; i++)
        {
            for (int j = 0; j < Columns; j++)
            {
                Vector2 spawnPos = new Vector2(transform.position.x + i * (BrickPrefab.transform.localScale.x + Gap), transform.position.y - j * (BrickPrefab.transform.localScale.y + Gap));

                GameObject brick = Instantiate(BrickPrefab, spawnPos, Quaternion.identity, transform);
                BrickController brickC = brick.GetComponent<BrickController>();
                GameManager gameM = FindObjectOfType<GameManager>();

                brickC.LooseEvent += gameM.OnBrickHit;

                _bricks.Add(brick);
            }
        }
    }
twin bison
rich adder
#

should directly spawn it as BrickController instead of GameObject , save a GetComponent

#
BrickController brick = Instantiate(BrickPrefab, spawnPos, Quaternion.identity, transform);```
#

you have to change BrickPrefab to BrickController type from GameObject

short hazel
#

I'd also rename the very abstract LooseEvent to something like in your example, Destroyed or something.
No need to specify "Event" in the name, as long as you name it as a verb in the past tense, it's directly visible that it's an event

queen adder
#

Thank you all very much. Very useful information UnityChanThumbsUp

stray badger
#

Hi, so what I want to do is make an object follow a point in space. The point in space can be thought of as a game object which is a child of the player, so when the player moves the point moves relative to the player hence moving the object to follow the player

#

I know how to make the follow part but how do I calculate the point in space?

wintry quarry
quick edge
#

Yo! I have a hard time understanding the difference between Rigidbody, CharacterController and the concept of Collider. Can someone redirect me to a good video for this or explain it to me ?

#

I didn't find any video CharacterController vs Rigidbody that explains the difference in details

rich adder
#

prob not videos but plenty of google results on unity asnwers/forums

quick edge
#

As I say I wanted a video

dim stream
#

Hi, I have just exported my first game but I have two problems, the quit button doesn't work and the menu text in unity is fine in size but when opening the executable the text is very small. If someone could help me I would appreciate it very much

swift crag
#

well, you won't always find a video

#

especially for things that you can summarize in a paragraph

rich adder
rich adder
swift crag
#

A collider defines the volume an object takes up. It can be a non-trigger, meaning it's an actual solid shape, or a trigger, which doesn't block objects and is only used to detect when things are overlapping.

A Rigidbody participates in the physics simulation. It can both affect and be affected by other physical objects. It's fully simulated by unity's physics system. Rigidbodies can collide with other objects if both of them have colliders.

A CharacterController isn't handled by the physics system. It's just a way to move around without going through colliders. A CharacterController includes a capsule collider.

quick edge
#

And I also searched for threads but I don't understand what is the "best". The general answer is "rigidbody" = physic, "CharacterMovement" = simple movement (without actually using physics)

swift crag
#

there isn't a "best"

queen adder
swift crag
#

which is best: apples or a power drill?

swift crag
dim stream
quick edge
queen adder
rich adder
timber tide
#

just start with rigidbodies

timber tide
#

and if you come to a part where you have to ask yourself how to do something differently, then you can consider the cc

queen adder
#

I always have a hard time making the camera follow a rigidbody Personally so i try to stick with CharacterControllers (Except in 2D)

swift crag
#

I haven't tried to do a first-person rigidbody controller before

queen adder
#

^^^^Thats my problem

swift crag
#

I know that can be a headache with jittery cameras

#

(even if you're interpolating)

queen adder
#

It always jitters

#

Idk about a 3rd person controller which is what i think oof is doing

rich adder
#

the old Standards assets used Rigidbody movement

quick edge
timber tide
#

if you like to do more work

queen adder
#

You gotta stop questioning it

#

And just try it brother

quick edge
#

I'm sorry but no

rich adder
swift crag
queen adder
#

I helped you like two days ago i think?

quick edge
#

This makes no sense

swift crag
#

you directly tell it how to move each frame

quick edge
#

Not to be mean

#

I just have more questions

swift crag
#

the only thing a CharacterController does is move you without going through colliders.

quick edge
#

It was kind of you

queen adder
#

its confusing tbh

swift crag
#

a non-kinematic Rigidbody can be shoved around by other physics objects

dim stream
#

if i have the executable, if i click on build it generates another executable or replace the first one?

swift crag
#

a kinematic Rigidbody is closer to a CharacterController, since it's not affected by physics forces

queen adder
#

You could also try a different game engine Dont ban me unity

rich adder
#

CC is like a mix of Kinematic RB and dynamic rb (velocity part)

swift crag
clear seal
#

am i going far like this or no?

swift crag
#

a CharacterController moves immediately when you ask it to.

swift crag
rich adder
clear seal
dim stream
#

if i have the executable, if i click on build it generates another executable or replace the first one?

swift crag
#

If you have five different states you can be in, you should use an enum, rather than five bool fields

#

as long as they're mutually exclusive

#

so if you can't be idle and ready and reloading all at once, you can just do this instead

clear seal
#

i am making a musket

rich adder
swift crag
#
public enum State {
  Idle,
  Ready,
  Reloading
}
timber tide
#

holding both f and q key hurts my fingers

swift crag
rich adder
#

too may for my taste

clear seal
rich adder
#

mind as well use && then

swift crag
#

I presume you're trying to simulate all of the various steps of reloading a musket

clear seal
clear pine
#

Heyo!

Can someone tell me if it's possible to query the current lobby a user is in to get data?

quick edge
swift crag
clear seal
#

and not keep holding it

swift crag
#

What is pressing those buttons supposed to do?

#

Change how the musket is being held?

clear seal
#

and what state it's on

#

very important

swift crag
#
private Grip grip;

private bool hasPowder;
private bool hasBall;
private bool hasPanPowder;

public bool CanFire => grip == Grip.Normal && Loaded;
public bool Loaded => hasPowder && hasBall && hasPanPowder;
swift crag
#

It might be like this

clear seal
#

wut

swift crag
#

CanFire is a property. It runs a method when you read it.

clear seal
#

um i think it's supposed to be like this

swift crag
#
Debug.Log("Can I fire the gun? " + CanFire);
#

that will print true if grip equals Grip.Normal and Loaded is true

swift crag
#

here's an equivalent

stray badger
swift crag
#
public bool CanFire {
  get {
    return grip == Grip.Normal && Loaded;
  }
}
#

You could also just make it a method, I suppose

#
public bool CanFire() {
  return grip == Grip.Normal && Loaded;
}
#

Properties are nice because you use them a lot like variables

#
if (Loaded)
clear seal
#

well

swift crag
quick edge
#

If I understand correctly. If I don't need realistic physics in my game it is more logical to use a CharacterController than a rigidbody because it will take less effort for the same result (better result) ?

swift crag
#

it's inappropriate if you need the player to be heavily affected by physics

clear seal
#

oh and should i use a get component to desactivate character controller and script?

quick edge
#

The problem is I don't know where to draw the line of "heavily" affected by physics or not

timber tide
#

Do you want to make your own physics or not

swift crag
quick edge
#

What does that mean ?

swift crag
#

You have to tell the CharacterController exactly how to move.

#

If you want to make the player rocket jump, you have to figure out how to make that happen yourself

#

you can't just use Rigidbody.AddExplosionForce

quick edge
#

Let's say I want to make a souls like. For me CharacterController is better because the game don't have that much physics, is that right ?

timber tide
#

probably

swift crag
#

I'm using a character controller in my own soulslike game, yes

timber tide
#

rigidbodies are really good for accumulative forces and high speed projectiles

quick edge
#

And I can make everything with the characterController, no limitation? Elevators, flying platforms, health system?

swift crag
#

a health system is completely unrelated to how the character moves

cosmic dagger
#

A health system has no relation to a character controller. Everything else depends on how you can integrate moving objects in regards to the character controller . . .

swift crag
#

The other two require some work.

#

If you want to do more advanced character movement, consider this guy

#

it's a free asset that implements a much more elaborate character controller

#

It does a great job of handling moving platforms

#

but it also requires more from you than just using a default CharacterController

quick edge
#

And I got a problem with that

swift crag
#

yes, because that's used to detect when you move into an object

#

this has nothing to do with things hitting your collider

rich adder
swift crag
#

A CharacterController includes a capsule collider, and you can detect when this collides with things using the usual physics messages.

quick edge
rich adder
#

OnTriggerEnter also works btw

quick edge
rich adder
#

or use a raycast / physic queries

timber tide
#

would be more specific to your weapon than the character

#

oh but to be hit right

rich adder
timber tide
#

can always just cast upon the weapons as well if you want specific hitboxes

quick edge
swift crag
rich adder
#

id love to know though

timber tide
#

for collisional purposes

rich adder
timber tide
#

you can however make your own continuous collider checking methods if for reason you're not registering the hitboxes between colliders

#

more likely to happen if smaller hitboxes, or quicker movements

cosmic dagger
quick edge
#

Is CharacterController something specifics to Unity ?

swift crag
#

It looks like a character controller behaves like a kinematic rigidbody

swift crag
#

So it will cause messages when it enters a trigger collider with a kinematic rigidbody

#

It will also...eventually cause a message when it enters a trigger collider without a rigidbody

#

it's inconsistent, though

rich adder
swift crag
#

And if a non-kinematic rigidbody hits it, collision messages can be sent

#

notably, not if the character controller tries to move into it

swift crag
#

it's weird

#

it notices, eventually

#

I think I'm relying on this behavior in one of my games. oops

rich adder
#

thats strange mine triggers the message as soon as edges intersect

#

or maybe im just remembering wrong 😵‍💫

#

I think OP was asking about if OnCollisionExit would work though, that afaik doesn't work at all on CC does it ?

#

Kinematic rb needs a dynamic for it on other collider, so maybe if the other collider had dynamic rb it would work on cc?

swift crag
#

both Exit methods work fine

swift crag
#

i get the proper messages when i drop the cube on the capsule

#

but if the CharacterController tries to move into the wall, it just stops short as expected

#

and no physics messages occur

rich adder
#

ahh so its basically like the other dynamic calls it just cause it hit Any collider, makes sense

queen adder
#

I'm making a space invaders game to learn the engine but for some reason I cant get the collision detection right. from the tutorials I've seen I don't notice anything wrong. can I please get help thank you in advance.

    {
        Destroy(gameObject);
    }```
rare basin
#

and trigger conditions for it?

swift crag
#

that link will walk you through all of the ways physics messages can go wrong

queen adder
#

Okay I'm taking a look at it now!!! thank you.

#

I SEE THE ISSUE I HAD TO WRITE OnTriggerEnter2D

#

TY GUYS

trail wharf
#

hello folks, I'm making a game that requires 5-6 on screen sticks, something like this, I have mapped 2 on left stick and right stick of gamepad, how to add other gamesticks for android ?

rare basin
trail wharf
#

I tried to connect using android gamepad stick but that's not working for some reasons, what to do?

rare basin
#

this is a code channel

trail wharf
#

I also entered in input system, this channels more experienced and active, saw someone asking raycast related question too so

rare basin
#

you have issue with

rich adder
trail wharf
short hazel
#

You might need some code to "redirect" the physical joystick input to your third virtual gamepad
Unless I didn't get your question

wary saffron
#

alright so i want to make a game i got the objects and stuff im just basically bored and stopped coding pre 2021 and im trying to get back into coding after on and off things for 3 years

#

basically i just need help creating graphic area and also other things and advice on it

#

i got the player controller its a litteral bean and it had sound attached to it

#

im trying to get to the more advanced part and boost my coding algoritem and combine different genres into one

#

and also art styles

#

cutsences and whatnot

trail wharf
# short hazel You might need some code to "redirect" the physical joystick input to your third...

So I'm using the 2 joysticks as I show here for movement and view, the third is for various player skill moves, and I'd like to make 2-3 more joysticks but only 2 are working right of the bat
I've mapped triggers of animations of skill moves to the third joystick too and initiated that in the player controller and it works with right stick but as soon as i make the third stick android stick or another, it stops working

sullen zealot
#

how can i get coordinates of click on button?
smth like this:

GetComponent<Button>().onClick.AddListener(() => Debug.Log(coordinates???));
bright hull
#

im doing an enemy AI but when I start game enemy is not coming to player. its going up

trail wharf
# rich adder the same way you added the first two sticks

can you tell me what I'm missing in this scenario dude,
#if ENABLE_INPUT_SYSTEM
public void OnMove(InputValue value)
{
MoveInput(value.Get<Vector2>());
}

    public void OnLook(InputValue value)
    {
        if(cursorInputForLook)
        {
            LookInput(value.Get<Vector2>());
        }
    }

I've made another vector2 for other skillmoves too
Problem is the joystick scripts from input function work for gamepad but not for other sticks

ruby barn
#

Does anyone know if Localization gives any event on change? I need to recalculate the rect transform depending on the new text

swift crag
#

You can listen to StringChanged on a LocalizedString

#

or use the OnUpdateString unity event on a LocalizeStringEvent, for something component-based

short hazel
rich adder
ruby barn
trail wharf
trail wharf
#

these are the 4 joysticks to be present as in game flick mechanisms and I'm using onscreenstick script as a way to link my input system to them
problem is onscreenstick only covers 2 gamepad sticks as part of it's stock functionalities i think and I need more than left and right gamepad stick, I need at least 5 2d vector sticks

rich adder
trail wharf
# rich adder wdym by gamepad and not other sticks?

I mean I can't link other 2d vector bindings to onscreentouch UI, like I've given zxcv as a keyboard composite and it works also if I have a onscreenstick connected to right stick of gamepad but not for other sticks available

rich adder
#

also why do you have the clone of the same script so may times

trail wharf
#

as far as my understanding goes

short hazel
#

I don't think that "On Screen Stick" components use the Actions Asset at all

#

Seems like they take a key binding directly

trail wharf
swift crag
#

unless those scripts are defining new controls for the input system to use, I wouldn't expect them to show up in the menu here

#

(i have never done such a thing before, so i'm not sure how that'd even work)

trail wharf
#

alright I now understand somewhat a lil bit more after reading this script, android stick it seems is controlled by the android section of the plugin, it's just not a drag and drop for other input bindings as is for gamepad and keyboard bindings
most of the youtube tutorials seem to doing with only 2 sticks since most games only require 2sticks, I'll see what I can make do of the android scripts and if I can cook something, most likely burnt toast incoming

green island
#

can i somehow dedect what deleted a gamobject because a gamobject gets deleted the frame that i spawn it and i dont know why

wintry quarry
swift crag
#

Add an OnDestroy method and log something in it or attach a debugger.

green island
swift crag
#

...i'm pretty sure that runs instantly when you destroy an object, at least

#

rather than at the end of the frame, when the object actually gets cleaned up

wintry quarry
green island
swift crag
#

this is where a debugger would be useful

#

break in OnDestroy, then step out to the culprit and look at the name in the debugger

green island
# wintry quarry how did you test that? Show code
 void Update()
 {
     if (!IsOwner) return;
     if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("Game"))
     {
         
         var player = Instantiate(playerprf);
         player.GetComponent<NetworkObject>().SpawnAsPlayerObject(OwnerClientId, true);
         player.GetComponent<PlayerMovement>().ch = ch;


         var cam = Instantiate(camprf);
         cam.GetComponent<CamaraMovement>().player = player.transform;
         cam.GetComponent<CamaraMovement>().CamerHolder = player.transform.GetChild(1);
         cam.GetComponent<CamaraMovement>().chatGo = GameObject.FindGameObjectWithTag("Chat");

         Debug.Log("deleted gamobject");
         gameObject.GetComponent<NetworkObject>().Despawn();
         Destroy(gameObject);
     }
 }```
green island
#
private void OnDestroy()
{
    Debug.Log("im dead");
}``` this funktion gets called
clear seal
#

i followed brackey tutorial about reloading

#

and

#

my reload time just dont exist

wintry quarry
clear seal
wintry quarry
clear seal
#

no cooldown i can still shoot

wintry quarry
#

!code

eternal falconBOT
wintry quarry
charred spoke
#

The part where you call the coroutine and the part where you check isreloading would be nice for a stsrt

clear seal
#
using UnityEngine;

public class GunSystem : MonoBehaviour
{
    public float damage = 10f;
    public float range = 100f;
    public Camera fpsCam;
    public ParticleSystem muzzleFlash;
    public AudioSource firedSound;
    //public ParticleSystem SmokeParticle;

    public int maxAmmo = 1;
    private int currentAmmo = 1;
    public float reloadTime = 13f;
    private bool IsReloading = false;

    void Start()
    {
        if(currentAmmo ==  1)
        {
            currentAmmo = maxAmmo;
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Shoot();
            muzzleFlash.Play();
            firedSound.Play();                   
        }

        if (IsReloading)
            return;
        
        if (currentAmmo == 0)
        {
            StartCoroutine(Reload());
            return;
        }
    }

    void Shoot()
    {
        
        //SmokeParticle.Play();

        currentAmmo--;

        RaycastHit hit;
        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name);

            HealthSystem target = hit.transform.GetComponent<HealthSystem>();
            if(target != null)
            {
                target.DamageEater(damage);
            }
        }
    }
    
    IEnumerator Reload()
    {
        IsReloading = true;
        Debug.Log("Reloading...");

        yield return new WaitForSeconds(reloadTime);

        currentAmmo = maxAmmo;
        IsReloading = false;
    }
}```
wintry quarry
#
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Shoot();```
#

you're just shooting no matter what when you click the mouse

#

I would expect you to check the IsReloading variable before shooting

#

I would guess that this part:

        if (IsReloading)
            return;```
Is supposed to be BEFORE the Shoot stuff
#

but you put it after

#

make sure when you follow a tutorial that you follow it exactly

charred spoke
#

I would not put it past Brackeys to have made this mistake and silently corrected it later on haha

clear seal
golden otter
#

i guess

charred spoke
#

They are also mostly garbage in my opinion

clear seal
#

and he stopped making vid 2021

#

so yeah

#

you are right

#

now i am in the fun part

summer stump
clear seal
#

animation🥳

clear seal
#

and natty

serene barn
#

hey, so I'm doing the junior programming lesson and I'm just wondering how do I rotate an object when it's on another object?

wintry quarry
#

you can rotate objects by setting their Transform's rotation or localRotation in code, or by calling the Rotate method on the Transform.

#

It all depends on the nature of the rotation you want.

serene barn
wintry quarry
#

the simplest thing would be to call Rotate on its Transform

#

obviously you'd need to do this every frame and you'd want to rotate at different speeds depending on what's going on

#

at a basic level something like:

propeller.transform.Rotate(0, 0, Time.deltaTime * throttle * propSpeedMultiplier);```
wintry quarry
#

Yes in Update generally

#

That's where you do things that need to happen every frame

cinder shoal
#

Thread

serene barn
wintry quarry
serene barn
#

of course throttle needs a value

wintry quarry
#

also Update needs to be capitalized

serene barn
wintry quarry
cinder shoal
#

That's not how that works

serene barn
wintry quarry
cinder shoal
#

You could use [SerializeField], but it'd already be exposed to the inspector since it's public right now

serene barn
#

oh shit sorry yea is would be public GameObject sorry

#

and then the name so the script can read it off the inspector

#

im dumb I dont even need the game object

#

line

#

I spent to long if this was that simple

polar acorn
serene barn
polar acorn
quick pollen
#

Is there a way to parent an object using script?

serene barn
#

Yes, I do, I create a line with public GameObject object; So i can add a hierarchy object to that box in the inspector

quick pollen
#

Or, to be more specific on what I want to do, I want to make it so whenever an object collides with an other, it kinda gets stuck to it in a way
parenting sounds like the easiest method

serene barn
#

so i refer to that object

polar acorn
serene barn
ivory bobcat
#

What's accepted for the most part: [Accessor] [Type] [Name]What you've done [Accessor] [Type] [Type] [Name]

quick pollen
#

online it said its a thing in gameObject itself

#

unfortunately its not what i want

#

thanks though

#

gotta think now

timber tide
#

can just set the position to the parent

#

or other gameobject directly

#
  • local offset
quick pollen
#

and I can unparent using transform.parent = null; right?

stray badger
#

!docs

eternal falconBOT
stray badger
#

This is for me

quick pollen
#

works better than I expected ngl

edgy fox
#

for LayerMasks does it only interact with hitboxes of that layer or does it interact with hitboxes of that layer and above

#

and is there a way to make rays more visible with Debug.DrawRay

wintry quarry
edgy fox
#

because this is outputting cheese when there are no objects with wallMask

wintry quarry
edgy fox
wintry quarry
# edgy fox

do Debug.Log($"Hit object {hit.collider.name} on layer {hit.collider.gameObject.layer}");

frigid sequoia
#

Can I create a method that takes a list and does stuff with it without specifying the kind of items the list may contain?

edgy fox
#

alright also is there a way to make rays more visible, theyre so small on my monitor I can hardly see them

#

ah got it

#

assigned the wrong mask in the inspector

frigid sequoia
#

Like a method that just takes a generic List and checks a variable on the List that all the different List do have even though they are not the same item

wintry quarry
edgy fox
#

now the only question is how that object is actually getting hit by the rays because the rays visible in Debug.DrawRay do not show it getting hit

wintry quarry
edgy fox
#

the green rays are the rays and the wall is the object

frigid sequoia
edgy fox
#

im so dumb

wintry quarry
# edgy fox

you need to do DrawRay(transform.position, new Vector3(....) * sizeX, Color.Green, etc..)

edgy fox
#

sizeX != 5f

wintry quarry
#

It has nothing to do with for loops

wintry quarry
edgy fox
#

yep I see it now

#

hmm but this one outputted into the console twice implying 2 of the sides hit it

#

it's a wall detection thing and each wall shoots out 1 raycast

#

and this shows it hitting as well

frigid sequoia
#

But then I can not call anything..., it gives a compiler error with the generic type

stable ore
#

why has this happened

#

plz help

frigid sequoia
languid spire
ivory bobcat
#

You could probably have T implied as the specific base type

frigid sequoia
#

I mean the code just lets you create List of items that can be active in the inspector and checks if X amount of them is active, I wanted to simplify it instead of making a copy pasted block of code of code for each one of them; what's the best way of doing that?

ivory bobcat
frigid sequoia
frigid sequoia
#

Wouldn't the generics just also work if you just do like public void MyMehod<InterfaceName>{} ; instead of adding a constrain or am I just wrong?

ivory bobcat
#

I'm sure you meant public Method(Type Name) but that wouldn't be generic

ivory bobcat
frigid sequoia
ivory bobcat
#

Then have it constrained as the specific class with the boolean variable/property

twilit pilot
ivory bobcat
#

Likely they all inherit/interface a base type with that field/property

frigid sequoia
twilit pilot
frigid sequoia
twilit pilot
#

I'd read about these before continuing - this is a perfect usecase for it and a good time to learn what they are

frigid sequoia
#

Yeah, I should relearn then, thx

true barn
#

Hi. I am having a Unity WebGL project and my prototype works on localhost. But after I released it to my server I cant connect via websocket. I can use a java client and connect to my websocket backend but I cant connect via WebGL. Is that a certificate issue maybe? Any advice on this? I have no iptables rules, dont use CORS and nginx rerouting should work fine as the ssl certificate seems to be working with my java client. Any tips are welcome.

ivory bobcat
wintry dew
#

How do i import a package for the Quaternion and other ones

languid spire
true barn
languid spire
#

not gonna work for WebGL, you need to write an Emsripten library to interface Unity with the JS Websocket code

true barn
languid spire
#

yes

true barn
#

but i thought nativeWebSocket impl switches to javascript in webgl?

#

(WebGL/HTML5 support)

languid spire
#

no idea, never looked at it but if it does not contain a Unity .jslib it ain't gonna work

true barn
#

but to be fair it doesnt work for me so.... i thought about maybe its an issue that i have to put the full chain ssl cert pem into my app?

languid spire
#

you using ws or wss protocol?

true barn
#

wss

#

its a letsencrypt cert

languid spire
#

that library looks ok, basic but workable, check your browser developer console for errors

true barn
#

Export.framework.js:10 WebSocket connection to 'wss://.../..' failed: Websocket error

#

thats all i get

hidden sleet
#

been fixing up my ui so it fits these dimensions, but my ui slots are incredibly small. is there some way to ensure that the width always matches the container?

true barn
#

403 in access log @languid spire but the path is correct..

ancient island
hidden sleet
#

not seeing anything related to stretch on rect transform, where should I be looking?

ancient island
hidden sleet
#

cheers

quiet gazelle
#

hello,

what is a good place to store downloaded assets? currently I moved all my assets to /Assets/Plugins, but for some reason some of those assets get moved to the root directory /Assets when project compiles.

languid spire
spiral narwhal
#

If I want a game object to animate from whatever rotation it has (could be random) to zero, how would I set that origin value in the animator? Or do I have to script it? If I have to use a script, should I use a Coroutine? Or some other way?

swift crag
#

I have a number of third party assets in Plugins (some of them imported themselves into that folder already)

#

I do not see why things would be moved.

ancient island
hidden sleet
#

I could work around it by manually setting the width and height but I feel learning how to do it automatically would be more beneficial

ancient island
swift crag
#

"Plugins" no longer appears on the list of special folders

spiral narwhal
ancient island
hidden sleet
swift crag
#

You then need to adjust the left/top/right/bottom values.

languid spire
swift crag
#

Picking an anchor preset changes the minimum and maximum anchor values, then adjusts the other settings to keep the recttransform at the same size.

ancient island
hidden sleet
#

yeah it should be

true barn
spiral narwhal
ancient island
ivory bobcat
#

You could always poll the progress of the animation if needed

spiral narwhal
#

Rotating the object from its current to the target rotation in each frame

ancient island
ivory bobcat
#

I'm assuming you're attempting to sync something relative to time with the coroutine

ancient island
hidden sleet
#

what does the right and left mean?

spiral narwhal
hidden sleet
#

since it's a stretch does that just mean essentially what the margin is?

amber nimbus
#

Hello, I have this simple code here but it doesnt work.
Debug.Log("Collision"); does work, but Debug.Log("Works"); does not work. I checked in the inspector while playing the game and the script is enabled so I have no idea why this would not work

ancient island
spiral narwhal
hidden sleet
#

changed it in the prefab but now in the actual screen it's still the same :/

#

hang on, got something else to try

ancient island
hidden sleet
#

nbm didn't work X/

ancient island
spiral narwhal
# ancient island you asked something about animations

My original idea was to use an animation to simply create two keyframes that "automatically" change from r to t without me having to do anything, but in order for that to work I would have to tell the animation clip that r is an arbitrary value of the game object, but I only find ways to set a set constant in the animation.
So I wasn't sure if that's possible in the first place, or if I should use scripting to achieve this problem

hidden sleet
#

back to square one. on the way

languid spire
true barn
ancient island
spiral narwhal
cosmic dagger
ancient island
hidden sleet
#

yup, just a good old panel

#

the rest was generated through the Scroll View option

spiral narwhal
spiral narwhal
ancient island
amber nimbus
#

Does the checkmark mean the script is enabled?

ancient island
ancient island
hidden sleet
amber nimbus
ancient island
hidden sleet
#

same as above

ancient island
desert elm
#

can raycasts travel inside 2d colliders?

ancient island
hidden sleet
ancient island
hidden sleet
#

seems like it's behaving strangely

desert elm
ancient island
hidden sleet
#

righty ho

wintry quarry
rich adder
hidden sleet
#

probably, didn't spot there was a ui channel

supple wasp
#

@queen adder

hidden sleet
#

will move over there if Zirok needs any more

ancient island
rich adder
eternal falconBOT
hidden sleet
ancient island
#

let's move to that channel, we dont want to bother

desert elm
amber nimbus
wintry quarry
rich adder
#

like not make it stop ?

supple wasp
desert elm
wintry quarry
rich adder
wintry quarry
#

you can also do a raycast towards the point from outside

desert elm
rich adder
#

if you have two points why you need raycast for distance?

queen adder
fierce marsh
#

there are two type of ray cast, mouse projecting ray cast and object raycast which projects from the center of the object

desert elm
# rich adder if you have two points why you need raycast for distance?

well, I do not have the second point-
sorry, explained it badly
To say in more detail, I have a point on the edge of a circle collider, and a point outside the collider. I need to raycast from the point on the edge of the collider to the outside point, so I can find a second point on the edge of the collider. Then, I want to measure the distance between the first and second points on the collider

fierce marsh
#

simply create empty game object as a position for the ray cast and make it a child for the main object

desert elm
#

oh I don't have a problem with doing the ray cast, I am just asking if it you can raycast inside a 2d circle collider until you reach the edge - and, from what the others have said, I cannot

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

public class PlatformAttach : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Rigid")
        {
            other.transform.parent = transform;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Rigid")
        {
            other.transform.parent = null;
        }
    }


}

I've created this code to make player stay on my moving platform, i made it move by using animator with "Animate Physics" Everything seems okay till the platform starts moving. Meaning that i cant move on it, my ability to move my player comes back after it stops. Whys that?

desert elm
wintry quarry
desert elm
desert elm
wintry quarry
#

The green?

#

Ok so what are you trying to figure out exactly with the Raycast?

#

And which object is t?

#

Also you're doing a Raycast by plugging in two positions, which is wrong

#

That would be a Linecast

desert elm
desert elm
shrewd swift
#

is there a way to debug and "see"/know what is modifying my player position
i checked all scripts, rigidbodies and colliders, and my player is moving down in a moment were it shouldn't, i cant find what is "making it going down"

wintry quarry
# desert elm the target/the red squares

Ok I think you're better off doing a RaycastAll here to get any interesecting forests and then just using the general mathematical formula for chord length to determine how much it overlaps the forests.
https://www.cuemath.com/geometry/Chords-of-a-circle/

A line segment that joins two points on the circumference of the circle is defined to be the chord of a circle. Explore more about chords of a circle with concepts, definitions, formulas, theorem, proof and examples.

true barn
#

@languid spire All i can see is a 403 when my GET call tries to upgrade to HTTP 1.1. And then in the next line the "websocket error" in console. Any last advice maybe?

desert elm
#

thats all I need to know

#

not another solution thats gonna take another hour to research
all I need to know is if the raycast would work

wintry quarry
shrewd swift
wintry quarry
#

And no it won't work

desert elm
wintry quarry
#

As mentioned it will interesect the circle immediately and give you a distance of 0

desert elm
swift crag
#

i do not understand.

ancient island
desert elm
#

right so if I make an edge collider like this it solves my problem got it

#

thanks for the help

dense root
#

So I'm trying to make a raycast to my square however it appears to not work as intended, any thoughts? I'm thinking it has something to do with the layer being set and/or the collider itself

void Update()
{
    if(Input.GetKeyDown(KeyCode.Mouse0)) 
    {
        Debug.Log("Mouse clicked");

        RaycastHit hit;

        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log("Object clicked: " + hit.collider.gameObject.name);
        }
    }
}
ancient island
dense root
#

I'd prefer to stick with Raycast since I'm already on this track, but thank you

ancient island
languid spire
dense root
#

Oh is that what it is?! @languid spire

languid spire
#

maybe, I dont do 2D but it seems logical

queen adder
#

I am trying to rotate an object towards another object, but the only way i can think to do that is through quaternion.rotate, which means i have to call it every single time in the update() method. is there any other way to cause an object to fully rotate towards the intended target?

#

(so that i can put it all in one function and only have to call it once)

swift crag
#

You can make it feel like you're only doing it once by using a coroutine, perhaps.

#

A coroutine lets you write a method that "pauses" until it gets resumed by Unity

#

on the next frame, by default

queen adder
#

so if i write a co routine with the quaternion. rotateTowards inside it

swift crag
#

Right. The coroutine would repeatedly rotate a little bit towards the target

queen adder
#

okay

#

how would it know when to stop

#

how do you end a co routine

swift crag
#

it could quit once the angle difference is almost zero

#

exactly zero is something I'm not sure you should test for here

#

Quaternion.Angle(a,b) measures the angle between a and b

queen adder
#

i see

#

i see i see

#

its for a rubiks cube tho, basically what i am doing to rotate the top layer is making a new empty gameObject, setting it to the middle piece on the top's position, and rotating the empty gameObject 90 degrees, and then making all other top layer pieces children of the middle top piece and rotating towards the empty game object

#

if that makes sense

swift crag
#

Since you can't just have a single fixed hierarchy, right

#

That sounds reasonable.

wintry quarry
swift crag
#

sticking things onto an empty and manipulating the empty can be a lot easier than doing the math yourself

queen adder
#

that is another problem i am having

#

how can i make it so that when i set their parent to the middle piece of that face, then rotate, and then unchild them, so that they keep the position and rotation they are in

hidden sleet
#

come across some tutorials that talk about a new input system that you get via a package, would you say it's best to use that moving forward as someone starting out?

wintry quarry
#

stick with the "old" system for now until you get better as a programmer

hidden sleet
#

alrighty then, I'll take your word for it

vernal minnow
#

I've figured out the aiming of my characters blaster, but for some reason he rotates based on his edge and not his center

scarlet hamlet
#

Hey people 🙂 I know this is just straight up maths, but do any of you know how to get the angle of a in Unity c#?
I have a two variables available: distance and height, but I've been stumbling a bit on getting Unity to return the angle itself

Does anyone here know the correct method? 😊

vernal minnow
#

How do I set the sprites center for rotating

hidden sleet
#

simply cause I'm watching a tutorial on implementing joystick movement and none of them cover anything without the new input system

wintry quarry
#

It's unclear what "distance" and "height" are in this image

#

maybe label them?

wintry quarry
#

Soh Cah Toa!

short hazel
#

Adjacent / Opposite

vernal minnow
#

Sin cosine tangent

short hazel
#

So tangent(opposite / adjacent)
Do note that in Unity trigonometric functions take in and return values in radians, that can be converted to degrees using the Mathf.Rag2Deg constant

vernal minnow
#

Yep

hidden sleet
vernal minnow
#

Like input.GetAxis?

#

Vertical/Horizontal or am I in the wrong thing?

hidden sleet
#

in this case I need an on screen joystick like mobile games do. I've been using my keyboard so far to test but I'll need to put the thing on an android app for the project but none of the content I've found explains that without the new input system

wintry quarry
#

since it's a built in feature of it

#

in the old system you'd have to build that yourself from basic UI elements and code

vernal minnow
wintry quarry
#

but you'll have to learn the basics of the new input system for that

hidden sleet
#

yeah, I think for the time being I'll go and use it. Player movement never needs to be complicated for this task as it's only a uni project that doesn't have a focus on the player controller, it's just movement on a flat plane. But for my own projects moving forward I'll stick to the old one

vernal minnow
#

How do I make my sprite character rotate at its center?

oblique ginkgo
vernal minnow
#

In code

oblique ginkgo
#

transform.eulerAngles = new(0f, 0f, angle);

vernal minnow
#

The sprite is rotating on its right side making his turning look funny

oblique ginkgo
vernal minnow
#

The sprite is the game object

oblique ginkgo
#

Can you send a screenshot in editor of the sprite with the move handle on the pivot setting

vernal minnow
#

Like the sprite sort point in the inspector?

oblique ginkgo
#

scene view

vernal minnow
oblique ginkgo
#

your move handle is on center mode not pivot

short hazel
#

Pivot / Local to see where it'll rotate around

vernal minnow
#

Does the same sadly

scarlet hamlet
oblique ginkgo
#

its most likely an issue with the sprite, like it having whitespace on the right side

oblique ginkgo
vernal minnow
#

transform.Rotate(new Vector3(0, 0, Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));

short hazel
#

Arrows seem pretty centered in that screenshot. Sprite is 1.5 square wide, and the arrow looks like it falls at around 0.75 squares

oblique ginkgo
#

try a different rotation method

#

transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z + (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));

vernal minnow
#

Lmao, it's still the same spinning

#

Actually that just reversed the direction