#💻┃code-beginner

1 messages · Page 87 of 1

static cedar
#

Ah, should have said that. I thought when you said state, you'd want different behaviours in each state (Player Run, Player Jump something).
In that case, doing what I said might be detrimental.

ruby python
#

Yeah I did the check. and it didn't output anything. I also tried it with .gameObject at the end of the check and it crapped out again. So I'm confused as to how it found the parent Transform but not the parent GameObject.

neon ivy
#

you can make custom operators?

static cedar
static cedar
short hazel
neon ivy
#

I'm more familiar with classes than structs so I think I'll try that

ruby python
#

Oh, sorry no, the null check didn't log anything because it found the parent of all the doorChecker objects I'm cycling through. So there was nothing null.

The other stuff that I put in worked fine (log and test renaming the object).

static cedar
#

In Update for example.

neon ivy
#

does it cause lag?

static cedar
# neon ivy you can make custom operators?
    public static bool operator ==(ScreenVector former, ScreenVector latter)
    {
        return former.x == latter.x && former.y == latter.y;
    }

Welp, once you made your own == operator though, compiler might wine a bit.
So you need to add these as well.

    public static bool operator !=(ScreenVector former, ScreenVector latter)
    {
        return !(former == latter);
    }

    public override int GetHashCode() => HashCode.Combine(x, y);

    public override bool Equals(object? obj)
    {
        if (obj is not ScreenVector screen_vector) return false;

        return this == screen_vector;
    }
minor roost
#

how do i flip camera

static cedar
# neon ivy does it cause lag?

No, but it can crash (i think) if you went nuts since it will eat RAM. So i guess it will still lag lol. The more fields a class have, the bigger the weight or memory.

short hazel
static cedar
minor roost
ruby python
short hazel
#

Because it has no parent

#

No other possible cases

#

a.transform.parent can be, and will be null when a has no parent

neon ivy
ruby python
#

Sorry, I'm just trying to understand. If it can find the parent Transform, which is a component of the parent GameObject, why does it crap out when looking for the parent GameObject but not the Transform? That's what is confusing me.

static cedar
short hazel
# minor roost ? so how

From the Inspector. Rotate it back to what it was originally (Z rotation to 0) and change the game view's aspect ratio from the "resolution" dropdown at the top-left

short hazel
#

So they don't all have a parent

languid spire
minor roost
#

cant find it

ruby python
#

I just added .gameObject to the 'null' check and it threw an exception. Which is even more confusing, because if it's null it should just log the error.

languid spire
#

no

short hazel
#

No!

#

It's .parent that is null!

#

Hierarchy is made with the Transform, so that one holds parent-children information

craggy lava
minor roost
#

found it

static cedar
# neon ivy <:UnityChanClever:885169594715746394> I'll see what I can do, I know the logic s...

If i have to put it in another way, instance of classes hang around. And someone needs to clean up the mess but still sticks a while.
If we're finished using structs, we would throw them away immediately. But with classes, it's like we leave them around the counter for a while until your mother asks you or your brother if someone uses it and then your mother realises, she have to throw it away cause no one needs it anymore. (There's no more classes that references it)

ruby python
#

Okay, still a bit confused about it tbh lol, but it's working now. Thank you for the help guys.

languid spire
ruby python
#

I'm trying. lol.

static cedar
#

When asking about why something doesn't work. Please mention if there's a red warning sign right in the console first and foremost. UnityChanwow

#

Also what's the name of the Exception, and the line it occured. UnityChanThink

short hazel
# ruby python I'm trying. lol.

Question for you. Given this code: someObject.transform.parent.name, which gets the name of the parent object in someObject - In the Hierarchy, the object in someObject has no parent. Which one of these will be null, to signal there's no parent?

  1. someObject
  2. .transform
  3. .parent
  4. .name
    One possible answer only
ruby python
#

lol. Wouldn't let me just put the answer. But 3.

short hazel
#

Correct

ruby python
#

I do understand that part. The thing that's confusing me is being able to find the transform, but not finding the transforms GameObject, if that makes sense?

short hazel
#

Find what Transform, the someObject.transform?

#

Or the .parent?

static cedar
#

The problem you had was that the parent is null. And you're trying to access the gameObject of a non-existant value from: parent.

ruby python
#

someObject.transform.parent - is found.
someObject.transform.parent.gameObject - is not found.

It's the difference between finding the two that's the confusing part.

short hazel
#

The first one - it's not found, because it's null

static cedar
#

parent wouldn't throw a NullReferenceException because it did it's job. It's giving you null or a reference to a transform object.

short hazel
#

Transform:parent returns null if the Transform has no parent, it's in the docs

static cedar
#

It only throws NullReferenceException when you try to get through something that doesn't exist.
That means that getting null by itself, isn't a problem, the problem is what you might do with it, which is where the exception is getting thrown. :0

short hazel
#
string str = null;
Debug.Log(str.Length); // NullReferenceException! 'str' is null, can't access its 'Length' variable
ruby python
#

Sorry, I really don't mean to sound really stupid, just honestly trying to understand the 'why' of it.

If the code can find the parent transform, which lives on the parent GameObject, why can it not find the parent GameObject?

I don't understand how the GameObject can be null if the Transform isn't. Does that make sense at all?

short hazel
#

It cannot find the parent transform, and it tells you that by giving you null

ruby python
#

But it can. It works fine finding the parent Transform, but not when I try to find the parent GameObject.

short hazel
#

What do you mean exactly by "find" here? Like being able to type it in the code?

#

It's vastly different than what can happen when the same code runs

ruby python
#
foreach (GameObject doorChecker in doorCheckers)
{
  Debug.Log("I am a door checker");
  if (doorChecker.transform.parent == null)
    Debug.Log(doorChecker.name + " has no parent");
  Transform doorRootObject = doorChecker.transform.parent;

Works fine, finds the parent Transform.

foreach (GameObject doorChecker in doorCheckers)
{
  Debug.Log("I am a door checker");
  if (doorChecker.transform.parent.gameObject == null)
    Debug.Log(doorChecker.name + " has no parent");
  GameObject doorRootObject = doorChecker.transform.parent.gameObject;

Throws an exception, can't find the parent GameObject.

This is the part I'm struggling to wrap my head around.

short hazel
#

It does not find the parent in the first block of code

#

doorRootObject will be null

ruby python
#

Well, it does. 😕

short hazel
#

No, it doesn't

nimble apex
#

if transform.parent is null , it is null, it gives an exception error because u said transform.parent**.gameobject**

short hazel
#

It does not throw an exception because because you're not doing anything with doorRootObject just yet

#

Try to access anything on that and you'll get the NullReferenceException

nimble apex
#

u used the null value

dry tendon
#

Heey, hi everyone... Could someone help me with this? ```cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class LoadingScreen : MonoBehaviour
{
private float loadingCanvasTime = 2.2f;

[Header("Drag")]
[SerializeField] private GameObject loadingCanvas;
[SerializeField] private Animator loadingCanvasAnimator;
[SerializeField] private Animator loadingTextAnimator;

void Start()
{
    StartCoroutine(CanvasTextFade());
}

private float time;
private IEnumerator CanvasTextFade()
{
    loadingTextAnimator.SetTrigger("ActiveLoadingFadeText");

    yield return new WaitForSeconds(loadingCanvasTime);       
    loadingCanvasAnimator.SetTrigger("ActiveLoadingCanvasFade");

    yield return new WaitForSeconds(0.3f);
    loadingCanvas.SetActive(false);
}

}```This code is responsible for controlling the initial loading screen of my game. As you can see, it takes 2.2 seconds to disappear from the start of the game. For this reason, I would like to create a function, similar to Start or Awake, that can be accessed from anywhere in the code within the project. When calling this function, I want it to execute 1.1 seconds after the loading screen starts. The purpose of this is to free up Awake and Start to achieve a smoother and more dynamic start. Maybe it’s silly… but I have the feeling that it looks less fluid when I call too many functions in Awake or Start.

static cedar
#

Let me put it like this, transform.parent gave you the answer I didn't found anything which is equivalent to null.
There's nothing stopping it from giving you that answer because it's completely valid.
You can do stuff like.

if (transform.parent == null)

Then deal with yourself.

Or if you try to use it anyways, the runtime will get mad like what happened with transform.parent.gameObject. You asked for the transform and it gave you its transform. And then you asked for its parent, it answered with null, it didn't have a parent. And then you tried to get gameObject with it, but the parent beforehand answered with null and it's having problems with that.

gameObject here isn't null, the parent is.

nimble apex
#

class.functionA.functionB.parameterA

if functionA is null

functionA.functionB will return an exception

#

because u used functionA to execute functionB

ruby python
#

!code

eternal falconBOT
ruby python
#
 foreach (GameObject doorChecker in doorCheckers)
{
Debug.Log("I am a door checker");
                
  if (doorChecker.transform.parent == null)
    Debug.Log(doorChecker.name + " has no parent");
    doorChecker.name = "ThisIsWhoseParentImTryingToFindAndMyParentIs" + doorChecker.transform.parent;
    Transform doorRootObject = doorChecker.transform.parent;
short hazel
#

The console will hold the essential information here

#

Look for "<some name> has no parent" messages

static cedar
#

Does null reference converts to "null"?

short hazel
#

Empty string, IIRC when concatenating

static cedar
#

Ah.

#

I never tried it, i always assumed that it does ToString() in the method and would just throw a null reference error.

short hazel
#

There is at least one more "DoorLocked (clone)" object that has been cropped out of the screenshot below

static cedar
#

And i always do object?.ToString() ?? "null" anyways.

short hazel
#

Yeah same, can be shortened down to obj ?? "null" in most cases. But watch out as ?. and ?? don't work properly with Unity objects (it bypasses their destroyed-but-not-null-yet state)

ruby python
short hazel
#

Try a more explicit version so it doesn't get drowned out by the other logs

ruby python
#

That's the entire console

short hazel
#

Use Debug.LogWarning() for example

ruby python
#

No 'no parent' entries in there.

short hazel
#

Put this before the foreach loop

foreach (var obj in doorCheckers)
{
    if (obj == null)
        Debug.LogError("There is a null object in the list!");
    else if (obj.transform.parent == null)
        Debug.LogWarning($"Object {obj.name} has no parent!", obj);
    else
        Debug.Log($"Object '{obj.name}' passed all checks, its parent's name is {obj.transform.parent.gameObject.name}");
}

I'm starting to think the code you're showing isn't the one that's executing

#

This will, for each object in the list, ensure they're "valid"

static cedar
#

$"Object '{obj.name}' passed all checks, it's parent's name is {obj.transform.parent.gameObject.name}"

#

Might as well add that extra bit in the sentence.

short hazel
#

Good point, edited

static cedar
#

It really does get converted to "". :p

short hazel
#

Nothing beats creating a whole solution to check. Also longest cast I've seen lol, 19 seconds

static cedar
#

I doubt it's the cast, it's the method.

ruby python
#

Everything came back as 'passed all checks' 😕

I seriously appreciate the help, even though I don't fully understand the why, I know the how, so for the moment that's good enough tbh. Really don't want to waste any more of your guys time. It works, so for now that's good enough.

static cedar
#

I was thinking if you tested it right after you fixed the bug lol.

#

That kinda just confirms it. :p

ruby python
#

Really do appreciate you guys taking the time, thank you.

short hazel
#

The second part of the sentence asks you a question, you did that on purpose didn't you
Note that dividing a vector by zero will produce an infinite vector, so check if you have any divisions in your code

fleet patio
#

quick question, HalfLIfe 1/2 style movement. CharacetrController or Rigidbody? (Multiplayer), custom groundcheck if CC or built in?

hidden sun
#

this explains everything. thank you

static cedar
prime horizon
#

Guys, I have a problem with my movement.
I can jump while my character is on the left side of the map as you see in the video, but there's an invisible wall on the right of the camera which makes my character's movement heavily limited. I can't even jump to the second platform on the right.

rich adder
prime horizon
rich adder
prime horizon
#

How can I do that? I'm new

rich adder
# prime horizon How can I do that? I'm new
 private void Update()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, 1000);
        if (hit.collider != null)
        {
            Debug.Log($"Hit Collider:{hit.collider.name} at Distance:{hit.distance}");
        }
    }```
prime horizon
rich adder
prime horizon
rich adder
#

strange..

prime horizon
#

Yeah...

rich adder
#

try remake new level in new scene see if problem is still there

prime horizon
#

Yeah I will. Btw do you want to check my charater prefab? Maybe I messed up something inside?

prime horizon
rich adder
#

why is there a horizontal box collider across

#

your player center is def messed up af

prime horizon
#

Oh yeah that's the fall detector

rich adder
#

no wonder ray wasnt accurate lol

prime horizon
#

I actually have problem with my charater before.

#

I followed this picuter in this morning

rich adder
prime horizon
#

Shoud I delete the father and make the Sprite the parrent instead?

rich adder
#

fix your pivot point first, if you add any objects dont put them on the root put them as child

#

set this to pivot

#

that fall detector is probably useless but move it to child object for now

verbal dome
#

I thought it already does that? Like tilting left/right when steering

#

WheelCollider.GetWorldPose gives you the orientation of the wheels

#

You can modify the quaternion it returns before applying it to your wheel visuals

prime horizon
rich adder
#

why you did not do any of the stuff I suggested?

#

I never understood that, i said a specific thing and you did your own thing lol

prime horizon
#

I just remake it, I put the charater sprite as root, the falldetector and the groundCheck as children and I set the option you showed me from Center to Pivot.
What did I miss?

rich adder
prime horizon
rich adder
prime horizon
#

Oh nvm

#

I just realized.

#

That fallDetector is not "is Trigger"

#

So that box is the thing holding my jump height

#

or maybe my script is wrong too. The box is supposed to stay there and can only move left or right with the player.

summer stump
#

GroundCheck being false means you are not on the ground. Which means you are jumping or falling

rich adder
#

yes why even have that thing

summer stump
#

If you want, you can check if the y component of velocity is negative to see if you're falling

if groundcheck == false && velocity.y < 0

prime horizon
#

I need that thing for the respawn. If I fall, my character hits the box and it will respawn.

rich adder
#

not good way to do it

summer stump
unreal imp
#

guys anyone knows how to make to set an object material and change it?my script is not working ``` Material m;
public Material m1;
public Material m2;
public Material m3;
Renderer r;
// Start is called before the first frame update
void Start()
{
r = gameObject.GetComponent<Renderer>();
r.enabled = true;
r.sharedMaterial = m;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.F) && m != m1)
    {
        m = m1;
    }
    if (Input.GetKeyDown(KeyCode.G) && m != m2)
    {
        m = m2;
    }
    if (Input.GetKeyDown(KeyCode.H) && m != m3)
    {
        m = m3;
    }
}```
rich adder
sage mirage
#

Hey, guys! In order to manage in my options scene with sliders my main menu music and main game music and sound effects separately do i have to use audio mixer?

rich adder
#

should

sage mirage
#

So, I will probably have master volume, main menu volume music, game volume music and sound effects volume something like that? I mean for groups in my audio mixer

unreal imp
summer stump
rich adder
rich adder
#

every other game does it

sage mirage
#

@rich adder Hey! But if I want to control my menu music and main game music with just a one slider then I will need only master, music and sfx groups with it's exposed parameters right?

#

I mean for main and menu music one slider and for sound effects another slider

rich adder
#

some separate it

#

eg In-game music maybe preferable but menu music might not

sage mirage
#

What is better to separate them or not?

summer stump
verbal dome
#

Like this? (front view)

prime horizon
sage mirage
#

As a player, I prefer to control them with just a single slider. Why? Because it's just more comfortable making it this way.

rich adder
#

but if it works whatevs lol

summer stump
verbal dome
#

Why not separate sliders and a master slider?

sage mirage
#

You mean slider for menu, slider for main game and master slider?

summer stump
#

What osmal said is the norm. Thay is what almost all games do
I thought that's what you meant too stelios haha
Of course have a master slider.
But also break it up

verbal dome
#

Yes, well that's what I was talking about, so did you try GetWorldPose?

sage mirage
#

Master is a group that is in default in audio mixer btw

verbal dome
#

With master I mean a slider that controls all the music mixer tracks, not necessarily the master track

#

Or channel, whatever they are called

#

(I don't really use Unity builtin audio - FMOD ftw)

summer stump
#

Fmod is great. I learned it in college before I even used Unity. Made music tracks on it and sent it to my DAW for fun haha

verbal dome
#

Yeah love it

#

@boreal tangle You are moving it in Start, that will only happen once

oblique torrent
#

is fmod a daw?

rich adder
#

audio engine

verbal dome
#

It's very daw-like

summer stump
verbal dome
#

Audio middleware is the term

boreal tangle
#

oh

oblique torrent
#

i see

rich adder
#

I have ableton Push is fooon

#

..ops enough offtopic myb

oblique torrent
#

fl studio 🔛 🔝 🥱

#

oh you cant even see the emojis

verbal dome
#

I have a Pro Tools lifetime license I got gifted from Avid but I haven't used it in 5 years lol

oblique torrent
#

🗿

rich adder
#

thats my starter :x

verbal dome
#

@boreal tangle Since you are working with physics/rigidbodies, move the code from Start to FixedUpdate

rich adder
boreal tangle
#

ok thank you

oblique torrent
#

no off topic

#

😤

rich adder
#

banned

verbal dome
#

So did you get it working? Are the wheels tilting?

rich adder
#

tilting wheels xD defines physics

verbal dome
#

You can do something like wheel.Rotate(0, 0, steerAngle) after using GetWorldPose

verbal dome
rich adder
#

do they? thought they only shift up and down

#

suspensions and alike

verbal dome
#

Just like you have to lean left/right when on a bicycle

#

When turning

#

To maximize [some physics term]

rich adder
#

ohhhh like side to side tilt yeah more common in 2 wheeler

#

idk why i thought front to back xD

verbal dome
#

Ok and I have told you how to do this

#

What is confusing you?

#

You should have separate objects that just hold the MeshRenderer of the wheel

#

Rotate those, don't touch the object that has the wheel collider

#

Why?

#

Looks like that's not possible, the wheel collider aligns to the parent rigidbody

weary lion
#

Hi, nooby unity coding question here.

I have this in my start function

Vector3[] verticies = new Vector3[4];
Vector2[] uv = new Vector2[4];
int[] triangles = new int[6];

verticies[0] = new Vector3(0, 1);
verticies[1] = new Vector3(1, 1);
verticies[2] = new Vector3(0, 0);
verticies[3] = new Vector3(1, 0);

uv[0] = new Vector2(0, 1);
uv[1] = new Vector2(1, 1);
uv[2] = new Vector2(0, 0);
uv[3] = new Vector2(1, 0);

triangles[0] = 0;
triangles[1] = 1;
triangles[2] = 2;
triangles[3] = 2;
triangles[4] = 1;
triangles[5] = 3;

Mesh mesh = new Mesh();
mesh.vertices = verticies;
mesh.uv = uv;
mesh.triangles = triangles;

GameObject hex = new GameObject("Tile", typeof(MeshRenderer), typeof(MeshFilter));
hex.transform.localScale = new Vector3(30, 30, 1);

MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
meshFilter.mesh = mesh;
meshFilter.sharedMesh = mesh;

hex.GetComponent<MeshRenderer>().material = material;``` 
The "Tile" game object gets created but the mesh is empty (See photo)
#

Could someone please help me

summer stump
weary lion
#

Nvm, asking the question made me realize that I used the gameObject variable instead of hex

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

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    private float horiMovement;
    private float vertMovement;
    private float movementSpeed = 5f;
    private float jumpSpeed = 5f;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

    }
    // Update is called once per frame
    void Update()
    {
            horiMovement = Input.GetAxisRaw("Horizontal");
            vertMovement = Input.GetKeyDown(KeyCode.UpArrow)? 1f * jumpSpeed : rb.velocity.y;

        
    }

    private void FixedUpdate()
    {
        
        rb.velocity = new Vector2(horiMovement * movementSpeed, vertMovement);


    }
}
#

Does someone know why the player cant jump with this code.

languid spire
boreal tangle
#

5.0f

gaunt ice
#

change the jumpSpeed to 10000f to see if the player jump

boreal tangle
#

ok

languid spire
#

correct and what value does it get 1 frame later when Update runs again?

#

change it to anything you like, player will never jump

boreal tangle
#

but if I hold it down shouldt it jump

rich adder
#

GetKeyDown is 1 frame process

languid spire
#

no, KeyDown only fires once

languid spire
#

exactly, which is 0

#

which is what is fed into FixedUpdate

boreal tangle
#

so getkey would work

languid spire
#

not really. You should use KeyDown to set the vertMovement and KeyUp to reset it

slender depot
#

hey, trying to get the mesh renderer from this video to work on my project but it doesnt actually render, any help? also can i link the video here directly?

boreal tangle
#

ok thank you

slender depot
#

here it is

#

so far ive copied the script from the description, made an empty object, put the mesh renderer in, assigned the default material, put the mesh filter in, then the script. nothing really happens after

slender depot
#

yeah, messed with the values while play was pressed too

#

for context im trying to make an educational thing for my college thesis around vector math and stuff so i need to visualize the vectors

#

need a way to be able to render arrows based on rng'd values

#

oh i guess more context im working in unity 2d

verbal dome
slender depot
#

oh, how should it look like?

verbal dome
#

It should be in front of the camera

slender depot
#

i have it under canvas, would that work?

verbal dome
#

Object at (0, 0, 0)
Camera at (0, 0, -10)
Object is visible

verbal dome
#

Canvas is for UI

slender depot
#

gotcha

#

hmm yeah camera is at default and this is the object

verbal dome
#

Create the object from scratch. It shouldn't have a RectTransform

#

RectTransform is for UI, it got changed when you put it in a canvas

verbal dome
#

Also not sure if that shader/material is going to show

slender depot
#

works now thanks man

#

doesnt show up before pressing play, is that normal?

verbal dome
slender depot
#

ok new problem

#

seems to render under my background, should it be placed after?

#

hmm even placing it after it still renders under

verbal dome
#

What is your background made of?

#

Like what components

slender depot
#

here you go

verbal dome
#

It's UI so it's rendered on top of everything else. Would make more sense to use a world object like you do with your arrow

#

SpriteRenderer for the background maybe?

slender depot
#

gotcha, also is there any quick way of making the arrow black?

verbal dome
#

(Take it out of the canvas too)

verbal dome
slender depot
#

gotcha

slender depot
verbal dome
slender depot
#

never mind im a dummy forgot to resize it lmao

#

how do i like scale it properly like with the canvas

near cargo
#

Hi! I created a settings menu to change the volume of my effects in the game. I created a mixer and this script to change the volume (also exposed the volume parameter in the mixer)

// using's omitted 
public class SettingsUI : MonoBehaviour
{
    public AudioMixer audioMixer;
    public Slider effectsVolumeSlider;

    public void Start()
    {
        float effectsVol;
        audioMixer.GetFloat("effectsVol", out effectsVol);
        effectsVolumeSlider.value = effectsVol;
    }

    public void SetVolume(float volume)
    { 
        audioMixer.SetFloat("effectsVol", volume); 
    }
#

Everything works fine if I run the game in the editor, but in the build, the volume doesn't change at all (if i go to the main menu and back to the settings menu the volume stays at 80db)

neon ivy
#

I have this interface:

public interface IEncounterable
{
    public static event Action<string/*encounterID*/, string/*encounterStateID*/> OnEncounterActivated;

    public void ActivateEncounter(string encounterID, string encounterStateID)
    {
        OnEncounterActivated?.Invoke(encounterID,encounterStateID);
    }
}

and I want to call ActivateEncounter() in this way:

  case ENCOUNTER_TAG:
                    string[] splitId = tagValue.Split(",");
                    if (splitId.Length == 2)
                    {
                        ActivateEncounter(splitId[0], splitId[1]);
                    }
                    break;

the script this code is in has IEncounterable but doesn't see ActivateEncounter() as a method.
am I missunderstanding interfaces?

summer stump
#

Also in unity, I don't think the c# version allows default implementations? But I'm not positive

solid zodiac
#

Hey everyone! Can you guys suggest a beginner unity tutorial? I've used to have experience with unity but it was 2015 or so hence most of the stuff I remember is irrelevant or outdated. I know basic C# and overall programming and my goal to make simple small games, mostly low-fi 2D. There's just too many videos and it's really hard to choose a single one from this whole plethora of content.
My requirements are basically:

  1. Something simple, I'm not going to use net code, advanced graphics or make complicated systems so I need something that's easy to follow and doesn't use redundant features.
  2. A preferably a series of videos, I think it's almost impossible to teach all important stuff in one video.
gaunt ice
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

summer stump
solid zodiac
neon ivy
#

well I don't, I just want to call that function

summer stump
neon ivy
#

I think I just don't understand how to use an interface xD

rich adder
#

interfaces aren't inherited 😦

#

don't wanna get all pedantic but diff between implementing and inheriting
when you "inherit" you are always restricted/limited to your. base class at the end of the day and you're only part of that "hierarchy"
Implementing is more modular and Many things can have something in common without being connected otherwise

summer stump
# neon ivy I think I just don't understand how to use an interface xD

Think of an interface as a remote control. The class human calls a method called change channel on the class television. Human doesn't need to know how the television implements that method. And tv can change how it implements it (like when they went analogue to digital) and still just show the "change channel" method. So nothing changes for Human

modest dust
#

Interfaces are more of a contract where you do a pinky promise that you'll implement the fields and methods of the interface into your class. So if you don't implement it then you won't be able to use it within the same class. Other classes can call these methods as they truly believe that you did what you had to do and implemented these methods as you should

#

I believe you can do "default implementations" but these will be just seen as virtual and you can override them and then use them

near cargo
rich adder
#

@modest dust interfaces only have props not fields but yea

modest dust
#

Ah yeah, props, my bad

rich adder
near cargo
#

wdym canvs scaler's?

#

you mean my slider's?

rich adder
# near cargo

did I misunderstand you can't move the slider in build ?

near cargo
#

I can move the slider in the build, but it wont write the volume to the mixer

neon ivy
#

ok I implemented the ActivateEncounter method but it refuses to let me Invoke the event...

unreal veldt
#

Hi guys, is anyone here knowledgeable in dialogue system?

near cargo
#

If i exit the settings menu and go back in it the slider will reset all the way to the right

near cargo
rich adder
neon ivy
rich adder
remote hound
#

Hey guys, I'm creating a basic 3rd person game with a static camera. I was wondering how I could get the player character to look wherever it's going, I've already scripted the movement. Thanks in advance ❤️

rich adder
remote hound
#

This was my attempt.... 🙂

neon ivy
near cargo
#

its just AudioMixer

near cargo
rich adder
near cove
#

hello anyone knows the formula for creating a random point at a specific distance from another point

rich adder
gaunt ice
#

dont cross post

short hazel
gaunt ice
#

r*random angle

near cargo
near cove
neon ivy
#

should I just make a singleton EncounterManager instead of an interface? xD

remote hound
rich adder
#

or is it just not setting at all

near cargo
rich adder
short hazel
gaunt ice
#

the code:

random quat*vector3(r,0,0);
```it should give you a random position on sphere surface
rich adder
short hazel
#

There's Random.onUnitSphere that can give out a random direction if you want!

neon ivy
near cargo
near cargo
#
    public void SetVolume(float volume)
    {
        Debug.Log("Setting volume to " + volume);
        audioMixer.SetFloat("effectsVol", volume);
    }
summer stump
#

@neon ivy
!code

eternal falconBOT
unreal imp
#

Guys, does anyone know how I can change the material of my model? This code does not work for me but in reality it does because in the debugs it is shown that it is fine but it does not change the material and I also want that if the material is the same as the material that I want to change, the code is not executed (eg: change color black the weapon but it already has black color so it does not execute) ``` Material m;
public Material m1;
public Material m2;
public Material m3;
//SkinnedMeshRenderer r;
// Start is called before the first frame update
void Start()
{
m = gameObject.GetComponent<SkinnedMeshRenderer>().material;
//m.enabled = true;
//m.sharedMaterial = m;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.F) && m != m1)
    {
        m = m1;
        Debug.Log("F pressed");
    }
    if (Input.GetKeyDown(KeyCode.G) && m != m2)
    {
        m = m2;
        Debug.Log("G pressed");
    }
    if (Input.GetKeyDown(KeyCode.H) && m != m3)
    {
        m = m3;
        Debug.Log("H pressed");
    }
}```
rich adder
#

and does dev mode print debug.logs? its been a while, i just use onscreen console asset

near cargo
#

yeah

#

it attaches the build to the editor

rich adder
#

ohok . so you see other logs but not that one ?

near cargo
#

i see the log

#

the SetVolume function gets called

#

audioMixer.SetFloat("effectsVol", volume);

#

but this line isnt doing anything

short hazel
#

Audio mixer volume operates on a logarithmic range, setting a value that is between 0 and 1 won't do much

near cove
rich adder
#

ah yes

#

you need to do Log10()

#

iirc

near cargo
remote hound
short hazel
#

Log10(vol) * 20 IIRC

near cargo
#

but why it works when i run the game in the editor

neon ivy
rich adder
near cargo
#

yes, and the volume changes accordingly

#

except in the actual build the volume doesnt change at all

#

so i change the slider's min max to 0 and 1 respectively and Log10(vol) * 20?

rich adder
#

so the value from the slider

modest dust
rich adder
modest dust
#

You need to add public static event Action<string/*encounterID*/, string/*encounterStateID*/> OnEncounterActivated; into your class and use that, not InterfaceType.Event

neon ivy
#

I'm just trying to force an interface into this while it really has no place being there

near cargo
#

yeah no change

modest dust
# neon ivy at that point I should just use a singleton to handle this event instead of impl...

Well, you need to understand that an interface is not an extra class slot to have extra inheritance. It's a contract to implement your own, custom behaviour for the methods and properties listed in the interface (so that two classes can both have, for example, a PrintDetails() method, both are called in the same way, but one prints details of how a car is made and the other prints details of a shopping transaction)

#

If a singleton is what will help, then go with it

neon ivy
#

all I wanted was to call an event from any script that has the relevant data

#

for some reason I thought interfaces were the way to go for that. but it's not

unreal veldt
#

Hi guys, any reason why it doesnt show the canvas for my Dialogue system? theres no error thats why i cant trace whats wrong

short hazel
#

The Mesh Renderer is disabled on that object

#

Not sure if that's intended, but that will "hide" the mesh

unreal veldt
#

but it will cover my NPC

#

look this is what happens

short hazel
#

If it's meant to just be a detection area, then it shouldn't have a mesh on it

#

Transform, Collider, scripts

neon ivy
#

if you want to visualize the range you can use gizmos

unreal veldt
#

like this?

short hazel
#

No Mesh Filter, no Mesh Renderer

unreal veldt
#

My problem is there is no error, i cant find the problem

#

I need to remove the mesh filter, renderer?

short hazel
#

Well yes, you don't need it to be visible, that will be more performant

maiden current
#

I have this script in the script execution order and It's not printing anything on the console. Why?

#

I also tried putting the Debug in an Start and as the first line of the Update but seems to not be working at all

gaunt ice
#

probably there is no instance of your script on gameobjects

maiden current
#

ooh

short hazel
#

"No asset usages" indicator above the class - yep

maiden current
#

So I need to have a gameobject with the script attached in the scene for it to work

rich adder
#

that would be an instance yes

maiden current
#

I see, thanks guys

near cargo
#
public class SettingsUI : MonoBehaviour
{
    public AudioMixer audioMixer;
    public Slider effectsVolumeSlider;

    public void Start()
    {
        if (PlayerPrefs.HasKey("effectsVol"))
            effectsVolumeSlider.value = PlayerPrefs.GetFloat("effectsVol");
        else
        {
            PlayerPrefs.SetFloat("effectsVol", 1);
            effectsVolumeSlider.value = PlayerPrefs.GetFloat("effectsVol");
        }
    }

    public void SetVolume(float volume)
    {
        Debug.Log("Setting volume to " + volume);
        audioMixer.SetFloat("effectsVol", Mathf.Log10(volume)*20);
        PlayerPrefs.SetFloat("effectsVol", volume);
    }

    public void GoBack()
    {
        SceneManager.LoadScene("MainMenu");
    }
}

this is my new settings controller, it doesnt change the volume mixer in the build, everything works as it should in the editor

near cove
#

`List<Vector2> edges = new List<Vector2>(pointCount);
Vector2 previousPoint = new Vector2(0, 0);

    lineRenderer.positionCount = pointCount;

    for (int i = 0; i < pointCount; i++)
    {
        previousPoint = edges[i] = UnityEngine.Random.insideUnitCircle.normalized * dist + previousPoint;
        lineRenderer.SetPosition(i, new Vector3(edges[i].x, edges[i].y, 0));
    }`
#

why is the edge index out of range?

short hazel
#

The list is empty. You need to .Add() elements into it. Can't access them with [i] to add a new element

#

Consider using an array Vector2[] instead, that is pre-filled with a set number of values

near cove
#

oh i see

maiden current
maiden current
#

Thanks a lot

elfin eagle
#

is it possible to get rid of the read only property?

true heart
#

how can i acess a scirpt thats on my player on a prefab? cause when i try to drag the player from the hierarchy to the prefab script it doesnt seem to work

viral hemlock
#

quick question does anyone know why after four seconds my game object doesn't tick back on

IEnumerator Untick()
{
    if(canUntick == true)
    {
        pointTrigger.SetActive(false);
        yield return new WaitForSeconds(4f);
        pointTrigger.SetActive(true);
    }
   
}
elfin eagle
short hazel
#

Coroutines do not run on disabled/destroyed objects, are you disabling/destroying the object this script is on?

polar acorn
viral hemlock
#

nope

#

wait yes actually lol

#

my bad

short hazel
#

Then it's prefectly normal for it to stop

#

Start it on another object

viral hemlock
#

ok

eternal needle
true heart
#

after i instantiate the object how to i plug in the refrences after

frosty hound
#

Get the components on the object and assign the things at runtime

true heart
stuck palm
#

why isnt this line of code making my character move? removing deltatime fixes it

rb.AddForce(movement * (moveSpeed * Time.deltaTime));

short hazel
#

Deltatime decreases the force by a factor of 100

#

The force is still there, it's just not noticeable

stuck palm
#

oh damn

#

setting the speed to like 1000 instead of 10 fixes it

short hazel
#

At a stable 60 FPS, delta time is 1 / 60 or 0.016

#

The time in seconds since the last frame

#

Using deltatime for applying forces is not recommended anyway. AddForce already smoothes out the force over a few frames

summer stump
#

When you need massive numbers like that, it is a sign you are doing things wrong/fighting the engine

stuck palm
summer stump
#

AddForce modifies velocity, which is in meters per second.

#

You do NOT want deltaTime in addforce at all

stuck palm
#

you can see a clear increase in speed when i focus on the gfame window

summer stump
#

AddForce is not dependent on frame rate

stuck palm
#

so why is the speed increasing then?

summer stump
stuck palm
#
void Update()
        {
            // Get input from the player
            float horizontalInput = Input.GetAxis("Horizontal");
            float verticalInput = Input.GetAxis("Vertical");

            // Calculate movement direction
            Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput).normalized;

            // Apply force to move the player
            rb.AddForce(movement * moveSpeed);
            isMoving = movement.magnitude > 0;
            
            magnitude = movement.magnitude;
            grounded = IsGrounded();
            _animator.SetBool(IsMoving, isMoving);
            if (isMoving)
            {
                // Calculate the rotation to look at the movement direction
                Quaternion lookRotation = Quaternion.LookRotation(movement, Vector3.up);

                // Smoothly interpolate the rotation
                transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 10f);
            }
            
             // Check for jump input
                    if (Input.GetButtonDown("Jump") && IsGrounded())
                    {
                        // Apply upward force for jumping
                        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
                        print("JAMPED!!!");
                    }
                    
            _animator.SetBool(Grounded, IsGrounded());
        }
#

this is my entire movement code

summer stump
#

You should also not use deltaTime in slerp haha. At least not multiplying it. Sorry

rich adder
#

iirc you still need it in the speed calc for inputs

stuck palm
#

i thought you had to use deltatime to make things more consistent across framerates

rich adder
#

like horizontalInput*moveSpeed* Time.deltaTime

#

i think

short hazel
#

That's why physics go into FixedUpdate, which by its name, runs at a fixed rate

rich adder
#

oh wait yeah also its in update nvm what i said

stuck palm
rich adder
#

rigidbodies movements go In FixedUpdate

rich adder
short hazel
#

It's more of a convention, poll input in Update, and deal with the Rigidbody in FixedUpdate

summer stump
short hazel
#

I'd also change the code that deals with the rotation to use rb.rotation, so it's consistent with the position changes you apply with AddForce. You'll experience less jitter as both will we applied at the same rate

stuck palm
summer stump
summer stump
stuck palm
#

which is what led me to believe that it was frame dependent

stuck palm
#

yeah i know now

summer stump
#

I mean... it's as simple as pointing to the calculation again

stuck palm
#

but befoer i asked i meant

summer stump
#

No I understand

stuck palm
#

anyway thanks guys

pastel sinew
#

Does someone know why my setup for buttons does not work? I cannot click on them for some reason.

short hazel
#

You need an Event System in the scene

#

It's added automatically when you create a Canvas, so you most likely removed it, add one back, it's what relays mouse events to UI objects

pastel sinew
#

And I already tried like two hours to fix it. notlikethis

stiff stump
#

i have this TileData class

[Serializable]
public class TileData
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Id { get; set; }

    public TileData(Tile tile)
    {
        X = tile.Position.x;
        Y = tile.Position.y;
        Id = tile.Id;
    }
}

and I have this WorldData class

[Serializable]
public class WorldData
{
    public List<TileData> Tiles = new List<TileData>();

    public WorldData(List<TileData> tiles)
    {
        this.Tiles = tiles;
    }
}

im trying to write the worlddata class to a json file using this static method

    public static void Write(object data)
    {
        string json = JsonUtility.ToJson(data);
        string path = Path.Combine(Application.persistentDataPath, "world.json");

        File.WriteAllText(path, json);
    }

but its writing {"Tiles":[{},{},{},{},{}]} instead of having the X, Y and Id of the tile in the list

short hazel
#

JsonUtility does not serialize properties, if I remember correctly

#

Oh and you'll have to provide a public constructor that has no parameters for both WorldData and TileData so instances can be created when using FromJson<T>()

queen adder
#

Hello, im fairly new to unity and game dev engines in general and im trying to get a player circle to slow down after the Keycode is let go by a dragforce, can anyone help me with this script?

#

Here it is so far ```
void Update()
{ while(rb.position.y > -3.5) {
if(Input.GetKey(KeyCode.RightArrow)) {
rb.AddForce(Vector2.right * speed);
} else if(Input.GetKey(KeyCode.LeftArrow)) {
rb.AddForce(Vector2.left * speed);
} else {

        }
    }
    Application.Quit();
}
frosty lantern
#

i'm trying to spread out object by having them lock onto points near the player rather than exactly the player.

    public Vector2 spreadPositions()
    {
        if (clump == false && ((Vector2)transform.position - chase).magnitude < error)
        {
            chase = (Vector2)target.position + UnityEngine.Random.insideUnitCircle * spread;
            return chase;
        }
        else if (clump == false)
            return chase;
        else
            return target.position;
    }
short hazel
#

llearn

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

I just added the while loop oops i never actually tested it, regardless im still wondering how to slow down movement by a dragForce is this answered in the tutorials?

frosty lantern
#

the objects that are lerping are all chasing the same point,

stiff stump
short hazel
#

Newtonsoft.Json is the most potent one when it comes to features

#

It's configured to serialize properties, but you can alter its configuration to use fields instead, if needed

stiff stump
#

okay thanks ill look into it

short hazel
frosty lantern
#

for some reason when i die, and my player is destroyed, the objects pan out though

queen adder
loud topaz
#

Simple One: Does OnTriggerEnter invoke all Colliders and how do i only use one of them? Setup on the right.

tender stag
#

how does one call a coroutine through an event?

#

would i just have to make a function and call it in there?

loud topaz
#

this is what i did.

short hazel
#

As the mesh collider is not a trigger collider, OnTriggerEnter will not be called for that one. So you can be 100% sure that when this method runs, it will be because of the box collider

tender stag
#

its annyoing that u cant call coroutines in an event

loud topaz
short hazel
#

Then it's not very good practice, and you should separate them into two child objects

true heart
#

if i only want to set my y rotation value but i dont wanna change the 2 others how would i do that?

short hazel
# loud topaz ah thx 🙂

You could technically see which one was triggered by storing references to them into class variables, and comparing them with the collider parameter of OnCollisionEnter, but yeah the general advice is to put multiple colliders on different objects

short hazel
abstract finch
#

What is the function in order to manipulate the rotation speed to where the value 1 means 100 percent rotating perfectly to the target and 0 means it will not rotate at all?

short hazel
#

Lerp?

#

Slerp (Spherical Lerp) for direction vectors and Quaternions

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

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    private float horiMovement;
    private float movementSpeed = 5f;
    private BoxCollider2D coll;
    private bool toJump = false;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();

    }
    // Update is called once per frame
    void Update()
    {
            horiMovement = Input.GetAxisRaw("Horizontal");
            if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded()) toJump = true;
            
    }

    private void FixedUpdate()
    {
        
        rb.velocity = new Vector2(horiMovement * movementSpeed, rb.velocity.y);
        if(toJump) rb.velocity = new Vector2(rb.velocity.x, 10);
    }

    private bool isGrounded()
    {
        
        if(Physics2D.BoxCast(coll.bounds.center, coll.size, 0f, Vector2.down, 0.2f))
        {
            Debug.Log("ground");
            return true;
        }

        return false;

    }
}
``` does someone know why the player does not jump?  I set it so the arrow key has to be pressed and the player has to be on the ground to jump. In the log it says the player is grounded but the player wont jump.
waxen adder
#

How do I seed random numbers?

abstract finch
slender nymph
waxen adder
#

I am indeed, ty

short hazel
short hazel
#

Then you of course have to make the third argument vary over time, so it transitions between the two rotations smoothly

abstract finch
#

Also I would like to add that I'm going to use an animationcurve to change the value of 1

#

1 being instant, 0 being nothing

short hazel
#

Yep curves can do that

abstract finch
#

awesome thanks

#

what if the lerp third argument is 2? wouldnt it just be the same as 1?

short hazel
#

Lerp clamps it to the 0-1 range. Use LerpUnclamped to bypass this restriction

frosty lantern
waxen adder
slender nymph
#

yes

waxen adder
#

ah ok. Glad I got that cleared up

frosty lantern
#

do you guys know what's wrong with the random chase vector i amd generating?

    public Vector2 spreadPositions()
    {
        if (clump == false && ((Vector2)transform.position - chase).magnitude <= error)
        {
            chase = (Vector2)target.position + (UnityEngine.Random.insideUnitCircle * spread);
            return chase;
        }
        else if (clump == false)
            return chase;
        else
            return chase = target.position;
    }
frosty lantern
#

it's not picking the points very randomly, it's locking onto the player position

#

wait i didn't accnt for null so it skips that? idk lemme see

true heart
#

if i only want to set my y rotation value but i dont wanna change the x and z how would i do that?

safe carbon
#

do you guys know why this is not working

#

void Update()
{
if(Input.GetMouseButtonUp(0)) {
Vector3 mouseP = Input.mousePosition;
//Debug.Log(mouseP.x + " " + mouseP.y);

       Ray ray = Camera.main.ScreenPointToRay(mouseP);
       RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);



       if (hit.collider.name != null) {

           //transform.rotation = Quaternion.Euler(0,0, - 48.068f);
           //transform.rotation = Quaternion.EulerAngles(0f, 0f, 80.976f);
           Debug.Log("CLICKED " + hit.collider.name);
       }
       

  
   }

}

wooden rivet
#

I'm trying to use the unity VCS to work on my project on two different computers. When I add the project as a remote project on the second computer there are some issues - I can mostly see the project as it was on the first computer, but any values I have set in the inspector (for serializedfield variables) are no longer defined.

Do I need to do something specific to check in changes made in the inspector? One computer is a PC and the other is a Mac if this is relevant.

slender nymph
safe carbon
#

YEP

#

smort

#

omg

slender nymph
#

and it's because you are checking the name property on a null collider

safe carbon
#

but i added box collider

#

to the object

slender nymph
#

sure, but what if your raycast doesn't hit anything

safe carbon
#

ic

#

what is the solution

slender nymph
#

check that something was actually hit by the raycast. RaycastHit2D has an implicit cast to bool that just checks if the collider is null so you can do that or you can check if the collider is null

safe carbon
#

alright thx

safe carbon
slender nymph
safe carbon
#

haha thxxx

tender stag
#

is it possible to grab a gameobject which access a certain method on a script?

#

lets say i have this RemoveHealth function

#

when i call this from another script i need to grab the game object which accessed it

slender nymph
#

pass the object as a parameter to the method

tender stag
#

yeah i was thinking of that

#

but im just wondering if theres a way to do it automatically

cosmic dagger
slender nymph
slender nymph
#

and?

tender stag
#

and i need to know which object, this object took damage from

slender nymph
#

yeah so you'll need to pass that to the method then

#

but i also don't see why you need the game object

tender stag
#

im making a damage indicator

#

and i need to rotate an ui element around the z axis towards that object

slender nymph
#

why does the RemoveHealth method need to know about that indicator?

tender stag
#

it doesnt

#

just the object which it took damage from

#

the indicator is in another script

slender nymph
#

so make the object that is dealing damage alert the indicator instead of the removehealth method

tender stag
#

oh wait

#

true

#

thank you

sly wasp
#

Hi, my Unity is stuck on Application.EnterPlayMode

slender nymph
#

you probably have an infinite loop

sly wasp
#

Is it something wrong with my script? (I’ll send it in a sec)

#

!code

eternal falconBOT
slender nymph
#

yep infinite loop in your coroutine

sly wasp
#

Dang

#

Thx

slender nymph
#

also, you're using FindGameObjectWithTag in Update, this is not exactly ideal. just store the reference either in Start/Awake or serialize it so you aren't constantly using that method. it's not as bad as just a regular Find, but you really shouldn't need to be doing that every single frame

sly wasp
#

I do that cuz if I have a different hoverboard active it will detect it automatically

summer stump
#

Doing it every frame TWICE

summer stump
slender nymph
#

Player.GetComponent<Character>().HoverBoardActive == false
just make the Character component know which HoverBoard is active and grab it from that instead. also instead of using GameObject variables, use variables for the components you actually care about

sly wasp
#

I’m good

unreal imp
#

Gayyssss (ejem guys) is there any form to make the player still crouch if it has a roof/object above him because the roof is smaller than his normal height?

eternal needle
tender stag
#

do colliders get checked from parent to child?

#

or child to parent

slender nymph
#

checked in what way

tender stag
#

like if im doing this

Collider[] objects = Physics.OverlapSphere(transform.position, secondRadius);

foreach(var collider in objects)
{
if(collider.gameObject.layer == LayerMask.NameToLayer("Damageable"))
}

slender nymph
#

the parent/child relationship of colliders is not relevant here

#

OverlapSphere will return all of the colliders it finds in the area specified using whatever relevant search filters provided (in this case none)

#

also if you only care about objects on a specific layer, then use a layermask

unreal imp
slender nymph
#

yes a physics query like a raycast or overlapsphere would be used for that

tender stag
#

if a collider is set as a trigger, will the overlap sphere still detect it?

slender nymph
#

depends on your physics settings or the parameters passed to your query

eternal needle
#

not entirely sure if thats the same case here

tender stag
#

im pretty sure i disabled it

#

which one is it

wintry quarry
#

"Queries hit triggers", as mentioned

tender stag
#

alright thanks

spiral narwhal
#

I just saw AudioSource.gamepadSpeakerOutputType in the docs. Does this mean one can play sounds on the PS4 controller?

wintry quarry
#

What do the docs say about it?

spiral narwhal
#

There still doesn't seem to be a code example though :/

zenith cypress
#

Grab audio source from code, set its gamepadSpeakerOutputType to GamepadSpeakerOutputType.Speaker, done.

shell herald
#

Sadly, my school forces us to have some Visual scripts and some c# scripts in our first semester, meaining, im not really good with any of them and it kind of confuses me how i can reference stuff over different kinds of scripts. My first question is, how do i replicate what i have in the first screenshot in c#. and the second is, how can i read the "score" variable in the second screenshot in c#

rich adder
#

GameObject.Find even in Visual Scripting 😬

shell herald
#

wdym?

rich adder
#

nothing lol

#

its easier to just learn c#

teal viper
shell herald
#

this is the script i have. i have a bow and want to only be able to shoot if i have more than 0 arrows and every time i shoot an arrow, it should add -1 to the arrow amount (score)

rich adder
#

the score itself should be Score

#

gameobject can be ScoreTracker or something like that

teal viper
#

Read the documentation

rich adder
#

You don't wanna have a GameObject.Find in update either, you would cache the reference in start or a field in inspector

sly wasp
#

Hi, I’m trying to make a random jump animation happen when I press up (I already have the jump function and everything, just need the random animations)

shell herald
#

the Thing is, i understand none of that, the documentation could aswell be alien language to me

chrome storm
#

Hello I would like some help with my coding :P

rich adder
chrome storm
shell herald
rich adder
#

you waited last minute 👍 nicee

rich adder
shell herald
#

nah, today was the class, tomorrow is the presentation

polar acorn
chrome storm
#

I need help with my unity game, I tried making a enemy AI jump attack from a video I saw but there's two problems I couldn't fix:

  1. Enemy won't flip to look at player
    2.enemy won't jump
rich adder
stiff stump
#

Tile tile = Resources.Load($"Blocks/{data.Id}") as Tile;
returns Blocks/{data.Id} -> Blocks/grass_tile
but its returning null

rich adder
#

please use a bin site !code

eternal falconBOT
teal viper
chrome storm
shell herald
teal viper
#

So the task does not require any mixing of visual scripting and C#?

chrome storm
polar acorn
eternal falconBOT
shell herald
teal viper
#

Seeing how you have trouble reading the docs.

#

Seeing how they didn't teach you any C# yet, I'd assume that the expectations from you are not that big, so maybe try to go for something simpler that you can implement in visual scripting

#

Don't bite more than you can chew

chrome storm
#

I feel stupid it still wont work. am i ment to sen a ss or something

eternal falconBOT
chrome storm
#

NVM did it

chrome storm
shell herald
#

The goal is to have a working prototype for a publishable 2d platformer by friday. i have playermovement, ui systems and everything in visual script since that was what was shown to us. i need to get enemy ai, a bow system, a sword system, weapon switching, and an arrow tracking system in there till then. i wouldnt mind doing it in visual script, however i do not know enough yet to be able to make it from scratch and in online tutorials/resources, nobody uses visual scrip so i have a hard time understanding it. Generally i find c# easier to understand, however i dont have the time to restart the entire project

rich adder
#

copy paste, send link

#

its not that hard

#

wtf

chrome storm
#

i already sent the code

rich adder
#

large code blocks should be pasted into a bin site

#

send link

chrome storm
sly wasp
#

How do I detect multiple animations using GetCurrentAnimatorStateInfo?

chrome storm
#

is that it?

#

😭 thank god

rich adder
#

did you set the ground layers correct btw

#

could you send link video you were following

chrome storm
chrome storm
teal viper
chrome storm
rich adder
#

make sure all layers are setup (also screenshot console window)

wintry quarry
shell herald
chrome storm
#

can i just say im new to coding soo..

#

do i need to type in debug.logs

#

or enable it on the unity screeen

timber tide
#

Debug.Log() or you can use VS debugger

rich adder
chrome storm
#

yeah... im more of a watch people make games and you will learn how to do it kinda person 💀

summer stump
chrome storm
#

im just trying my best

#

anyways here me ss

#

i think u wanted the debugger enabled and see the control pannel

summer stump
chrome storm
#

yeah im not quite sure what that is

summer stump
chrome storm
#

ik that but im not sure what they do, theres usually only 1

true pasture
#

can i rename the values in a vector2. Instead of x and y I want them to be min and max in the inspector.

#

I like having them both on one line to save space is why I want to use vector2

timber tide
#

Make your own vec2 struct

#

wont be on the same line though. That's some editor script stuff

true pasture
#

well thats really the only reason I wanted a vector2

#

i can live with xy tho

timber tide
#

take a look at those and see if it's offered

#

usually you can just plug those in your scripts

true pasture
#

okay that looks promising ty

timber tide
#

that looks pretty neat

true pasture
#

ah perfect lol

#

kinda weird unity doesnt have stuff like this on its own

timber tide
#

YEP

static cedar
#

Oh he already posted a pre made one.

unreal imp
#

guys help me? I am trying to solve the error of the player crouching across an object when he tries to stand up but on top of it he has a ceiling that is lower than his standing height. I did it with a raycast but now it gives me an error that I am going to send there ( code: https:/ /gdl.space/fasakiqawu.cs )

unreal imp
#

I think it generates a conflict between both parts of scripts

rich adder
#

there is nothing on 73 in the code you sent

#

you're missing the namespaces so sending without them is useless telling the line (•_•)

unreal imp
#

if (!characterController.isGrounded)

rich adder
#

the only error there is characterController is null

#

so either you have a copy somewhere or this object doesn't have a char controller on it

sly wasp
#

I have
public AudioClip[] myAudioClips;

How do I set the certain audio clips with resources.load?

rich adder
#

did you search the docs?

#

do you know how to assign something to a specific element of array?

wintry quarry
wintry quarry
#

Fix your car model it was exported or imported incorrectly

ivory bobcat
#

What have you tried?

rich adder
#

is this supposed to be steering? what are those arrows lol

ivory bobcat
#

Looks like there's an expectation of rotating and translating (moving)

round scaffold
#

is there a way to make interface implementations not give u the annoying large exception thing

ivory bobcat
cosmic dagger
round scaffold
#

all the fields are part of the interface

#

i want it to jsut set it as the usual property

#

like {get; set}

ivory bobcat
#

Interfaces do not have field members

unborn moon
#

i have this game object as UI object
how can I get its position?
I tried to use rect.transform.position and transform.position
but its position is not same as my

                Vector3 mousePosition = Input.mousePosition;
                Debug.Log("Event Data Position: " + mousePosition.x);
rich adder
#

that would be part of the suspensions though ?

eternal needle
cosmic dagger
rich adder
#

tires don't tilt on a 4 wheel vehicle, commonly its the suspensions that tilt the carriage. They're meant to stay flat on ground look at thread/shape of a motorbike vs car

round scaffold
#

no i just put the i to say its an interface propeties lol

round scaffold
#

thank u bear on a lightpole

boreal tangle
#

does someone know how I draw a ray so that it starts from the top right corner of the collider and stops at the bottom.

rich adder
unborn moon
# cosmic dagger use `anchoredPosition` . . .

I tried to click on the middle position of the square, but the output isn't seem like that

    if (Input.GetMouseButtonDown(0))
    {
        Vector3 mousePosition = Input.mousePosition;
        Debug.Log("Event Data Position: " + mousePosition);
         Debug.Log("rect.anchoredPosition.x" + rect.anchoredPosition);
    }
            
boreal tangle
rich adder
#

or I think you can just use size? you need a bit of math with that

queen adder
#

public static class SystemCollectionExtensions
{
    public static T TryDequeue<T>(this Queue<T> from) where T : Object
    {
        T ret;
        do ret = from.Dequeue();
        while(!ret);
        return ret;
    }
}```is it fine to use in an object pool made of queue?
boreal tangle
#

I meant bounds doesnt have an x or y when I type it in visual studios

boreal tangle
#

Debug.DrawRay(new Vector3(coll.bounds.extents.x,coll.bounds.extents.y),Vector3.down *coll.bounds.extents.y ,color);

rich adder
#

I think you add from center first

teal viper
ivory bobcat
rich adder
boreal tangle
#

thank you

paper rover
#

General question, is there a simple function to static batch objects that are instantiated? I have larger objects that spawn later and they aren't being batched

queen adder
#

oh i see

#

the problem arise when theres only 1 item, and it's null

ivory bobcat
#

Aye

queen adder
#

ig i can just get rid of the ternary and just let the entire extension to handle every case

paper rover
#

apologies

ivory bobcat
#

You could probably just do while count greater than zero T ret = dequeue if ret not null return ret return problem

queen adder
#

    public static T TryDequeue<T>(this Queue<T> from, T desperateReturn) where T : Object
    {
        T ret = from.Dequeue();
        while(!ret && from.Count > 0)
        {
            ret = from.Dequeue();
        }
        return ret ? ret : desperateReturn;
    }```maybe this is better
#

lemme logic test

cosmic dagger
queen adder
#

yea, should work, lemme actually run it

unborn moon
queen adder
#

ahh the instantiate will be called always ig, yea i dont want that

unborn moon
#

i mean i want to sync it with my mouse position

queen adder
#

I can maybe just use a func hehe

cosmic dagger
unborn moon
#

i want to get that object position output that is same as my mouse position when click

ivory bobcat
#

Log the mouse position and anchor position. Likely one or the other isn't within the same coordinate space.

queen adder
#
t = floatingQ_ws.TryDequeue(() => Instantiate(template_ws, transform, false));
```this pool looks better than the original ![UnityChanwow](https://cdn.discordapp.com/emojis/885169594879320064.webp?size=128 "UnityChanwow")
#

    public static T TryDequeue<T>(this Queue<T> from, System.Func<T> desperateReturn) where T : Object
    {
        T ret = null;
        while(!ret && from.Count > 0)
        {
            ret = from.Dequeue();
        }
        return ret ? ret : desperateReturn();
    }
```the pool btw, if anyone wants
cosmic dagger
unborn moon
cosmic dagger
ivory bobcat
unborn moon
queen adder
unborn moon
#

oh wait

#

somehow I get the problem

#

lemme see

ivory bobcat
#
    public static T TryDequeue<T>(this Queue<T> from, System.Func<T> desperateReturn) where T : Object
    {
        while(from.Count > 0)
        {
            T ret = from.Dequeue();
            if (ret)
                return ret;
        }
        return desperateReturn();
    }
queen adder
#

that looks cleaner and simpler, rigt

unborn moon
#

I solved the problem

queen adder
#

lol im writing it too complicated

unborn moon
#

idk why

#

but seem the value is different when its Awake and Update

eternal needle
gaunt ice
#

Queue has a trydequeue method btw

calm coral
#
[SerializeField, Required] CinemachineVirtualCamera virtualCamera;

internal void ToggleCamera(InputAction.CallbackContext _)
{
    virtualCamera. // is there a field or property to access that "Body" ?
}
```Hey, how do I modify body selection of `CinemachineVirtualCamera` using scripts?
*Don't ask to ask:* ||The main goal is to make some toggle button to switch between 1st and 3rd person camera view||
wintry quarry
calm coral
abstract finch
#

What is the function that uses speed rather than duration needed to get to a rotation? Right now im using Quaternion.Lerp but i would like to set a flat speed instead.

wintry quarry
wintry quarry
calm coral
#

A simple solution but I was forcing scripting way, meh... ThinkHmm

paper rover
#

I am trying to run Lightmapping.BakeAsync(); but it is saying it is not allowed in play mode. Is there an easier way to bake the lighting during the game?

queen adder
#

Hello. I've got this problem I still couldn't resolve. I have a .txt file with 4 million words in it and my script is supposed to display a random excerpt from it when I press C. But the first time I press it, sometimes, but not every single time, the game freezes for a couple of seconds. How could I fix this?

#

This is basically my code. And I've yet to find a way to fix this.

#

Any idea or workaround would help.

wintry quarry
#

Thus making a 4 million element array

queen adder
#

Could this be the problem?

wintry quarry
#

...yes?

#

Of course it is

queen adder
#

Ok, I'll try it, thank you.

#

I mean, I'll try removing the split and test it :))

eternal needle
#

I remember seeing you ask this before, but just curious why do you even need such a large file? What 4 million words could you possibly need

wintry quarry
#

The split is less of a problem than loading such a huge file in the first place

#

I/O is notoriously slow

queen adder
wintry quarry
#

The English language has like 300k words max

queen adder
#

They're stories and what not.

wintry quarry
#

But you're just picking a random word

eternal needle
#

Script isnt loading for me so I cant see what you're doing with the file, I think you would have a better time splitting each story into it's own file

queen adder
#

Oh, I deleted it, sorry.

#

I'll repost it.

#

But won't that cause even more problems?

#

I mean, I could split the .txt file in 4, 10 or 40 files, but wouldn't cycling through them cause even more freezing problems? And even more often?

timber tide
#

well, depends how you're loading it all in

eternal needle
#

Why would you cycle through them? You just wouldnt be loading 4 million words at once, you would be loading way less

#

That coroutine also doesnt need to be a coroutine, since its just yielding after all the code has run

fierce shuttle
queen adder
#

I'll try splitting it in multiple files, thanks.

#

can someone help fix my code?

#

i donr even know any languages fully

#

¯_(ツ)_/¯

verbal dome
vast vessel
#

Can someone help fix my cod!?!?!?!
-dosnt provide the code
-doesn't provide the error
-doesn't know what they are doing
-🤷‍♂️

queen adder
#

i diddnt want to spew my code here

verbal dome
#

No one will commit to helping you without seeing the problem first

vast vessel
#

How would people know if they can help, if they dont know what you want help with

teal viper
queen adder
#

did you not even read my message

#

smh

teal viper
#

You're probably expecting some "private help". This is not the place for that. Some people do that as a job and get paid.

rich adder
vast vessel
#

Im guessing you didn't even look it up on google or try to debug it

proper flume
#

!code

eternal falconBOT
gusty void
#

hi, I need an item button box to open under my pickup script. does anybody know why this may not be happening? ive looked through the tutorial a few times, I i think I'm just not understanding

honest idol
#

i was wonder how to turn my mesh into a ragdoll if that is possible

eternal needle
eternal falconBOT
gusty void
#

okay thank you!

eternal needle
honest idol
eternal needle
#

assuming you made the model

eternal needle
#

After that part, making a ragdoll is quite easy. theres a lot of tutorials online for it, but the general steps are
use the ragdoll wizard
disable all the ragdoll colliders, make the rigidbodies kinematic
enable colliders, make rigidbody not kinematic when you want it to ragdoll, disable the main movement code

honest idol
eternal needle
honest idol
eternal needle
honest idol
queen adder
#

Hey yall i got a question.
In my current project i have a level select screen.

I opted to make it a scroll view so the player just has to scroll up to see new levels or down to see previous levels. (Something like the candy crush level layout).
My only issue is. Im trying to save the level that the player is currently on.
Eg. If they on level 50 and they exit the game and go back into the game i want the level to show as level 50. I dont want it starting at level 1 again and then they have to scroll all the way back up to level 50.

So does anyone know how i would be able to save the position of the current level the player is on?

My levels are not prefabs. They are images that have a button script on them. And i setup my level layout (type of board, goals, etc) in a scriptable object

Sorry for the bad explanation. Im not sure how to ask this question.

Im using unity and c#

fierce shuttle
# queen adder Hey yall i got a question. In my current project i have a level select screen. ...

Are these images contained under 1 parent/container or in an array that references the image in the scene? If so, you could use the level number as the index (with respect to 0-based), and scroll to the image at that lvl number, otherwise, you could save the Vector3 of the anchored world position if its UI, or world position otherwise, though I feel like there should be other ways you can compress your data aside from relying on 3 floating point values

teal viper
queen adder
# fierce shuttle Are these images contained under 1 parent/container or in an array that referenc...

I made a scroll view in my hierarchy and it auto gave me a view port, content, scroll handle etc
I made my images in the content section.
I think my scriptable object for my levels is an array. Sorry i made that quite a while ago. So im not 100% sure.
I made a scriptable object called world. Then another one called level.
In my world SO i think i select how many levels i want the in my level SO i do the setup of my levels (moves, goals, layout etc).

Im not by my pc right now so i could be wrong.

queen adder
cerulean crypt
#

I have an issue. With my game, I start with an object disabled. Later, it's then enabled using SetActive(), however it doesn't then loop Update()s, it just does nothing. Do I have to kickstart it running updates through it or something?

queen adder
eternal needle
native seal
#

So I'm making a game where you cook foods and give them to customers, I store the foods that are in your inventory as a list of gameObjects. I made a customer scriptable object that has a list of potential "Foods" (another scriptable object). How would I check if the player has the corresponding food in their inventory? This doesnt seem to work

cerulean crypt
teal viper
eternal needle
#

Checking the gameobject looks like it added more complication

native seal
#

heres what my customer looks like

eternal needle
native seal
#

the .GameObject didnt work

#

here's what I came up with. It works but I want to know if theres a better way

eternal needle
#

the better way would not be storing a game object at all, and just be storing the FoodScript directly. Otherwise, this seems relatively fine

#

storing a list of food script would avoid N get component calls

native seal
#

ah so like its one layer less abstracted you could say

rich summit
#

What's the operation to add/substract (not set) to an int variable?

eternal needle
rich summit
#

Red line

summer stump
#

And what is the goal of that line of code?

#

If you want karma to be 5 less, then you want -=
But that IS setting...

rich summit
#

I do not want it to be set to -5 but rather go down by 5

summer stump
summer stump
honest idol
#

Hello again, I need some help with my script my keys A and D are inverted and im not sure how to fix it, The character also moves pretty slow and was wondering if there is a way to speed it up.

slender nymph
#

you have a negative sign in your multiplication for horizontal movement

eternal needle
honest idol
summer stump
gaunt ice
#

a is left and d is right
and dont multiply the output of GetAxis with deltatime

slender nymph
#

as for it moving really slow, you currently only move 1 unit per second because you are not scaling by a speed variable

rich summit
honest idol
summer stump
honest idol
slender nymph
#

scaling = multiplying

queen adder
#

i suggest making it a controllable variable too, then you can think about adding walk speed, sprint speed, crouch speed, etc

verbal dome
honest idol
#

does someone have a good video on making a self balancing ragdoll character all the videos I'm finding either don't help me or is not what I'm looking for

eternal needle
#

The general steps are to have an animated version of the player, then your ragdoll tries to copy the rotations. Movement likely would just be with AddForce

honest idol
eternal needle
# honest idol mhm ok I'll work on other stuff then, thank you

If you do specifically need to use an active ragdoll, I can try to advise more on it. If you just need something that can ragdoll then what I said a bit above about enabling the ragdoll is a lot better. No matter how much I fine tuned my ragdoll, it never really looked clean with its movement. Theres a good reason active ragdolls arent in many games as the main character. Sometimes they are just animation driven, which I feel is no longer an active ragdoll because it wouldnt respond to forces then

honest idol
eternal needle
#

Those games may look simple due to the goofiness, but trust me they are really difficult to make

#

From my experience as well, an active ragdoll is an absolute nightmare in multiplayer. I abandoned that project I was working on

honest idol
eternal needle
honest idol
molten portal
#

could someone drop me link of unity networking discord server?

slender nymph
molten portal
verbal dome
#

Be prepared for a lot of head scratching. It's definitely an advanced topic

#

As bawsi explained, the usual way is to have a normal animated rig and another rig that copies the rotations from the source bones to the joints. This is where the methods I linked become handy

gaunt basin
#

how do i fix this gui.Text = "My Variable: " + playerHealth.ToString();

#

the variable works idk whats wrong