#💻┃code-beginner

1 messages · Page 155 of 1

rare basin
#

into a list of instance ids, list of something else

lean basin
#

I would if there is no way to check if those int belong to instanceID or not.

#

but if there is why not? the game logic doesn't need to know if it belongs to a component or not

hexed terrace
#

You still haven't answered WHERE this list comes from

rare basin
#

i still have no clue what are you trying to do

drowsy totem
#

as discussed in this stackexchange thread, Time.time may start becoming inaccurate after a 9-hour playsession
https://gamedev.stackexchange.com/questions/141807/what-happens-when-time-time-gets-very-large-in-unity

if you want to keep a running timer / ticker for whatever reason, is there a recommended way to do it?

some examples:

timer += Time.deltaTime * rate;
while (timer > 1.0f)
    timer -= 1.0f;

timer += Time.deltaTime * rate;
timer = timer % 1f;

if(Time.time - startTime > 1f) {
    startTime = Time.time;
}

I think the first two give more or less the same end result, while the third one might run into inaccuracies in long play sessions. Thoughts?

rare basin
#

and for me it seems that your entire debugging structure is implemented incorrectly

#

why do you have a list of ints that has instance ids and other things

gaunt ice
#

so you can split it now, since you dont know where the int from and the int can be instance ID (false positive)

rare basin
#

and want to separete what is instance id what is not

lean basin
rare basin
#

how do you add elements

#

to that list

#

just make 2 lists

#

one for instanceIDs

#

one for random things

#

why are you putting everythnig into one list, then trying to figure out what is what wtf

#

why are you making your job harder 😄

lean basin
#

hmm maybe I should show a code? I don't know if it can explain what I'm doing.

// This is a class that handle an action that might be requested by multiple entities.
// It prevent a disabling of an action when only one entity is finished it's request.
[System.Serializable]
public class RequestAction
{
    // Triggered when requestList.Count is changed from 0 to 1.
    public UnityAction onActivated;
    // Triggered when requestList.Count is changed from 1 to 0.
    public UnityAction onDeactivated;
    // Triggered when requestList.Count is changed between 0 and 1
    // true is the same with onActivated, false is the same with onDeactivated
    [InfoBox("Please only connect this with code, thank you!")]
    [HideInInspector] public UnityEvent<bool> onStatusChanged = new();
    [ReadOnly, HideInInspector] public List<int> requesterList = new();
    bool currentStatus = false;
    public void AddRequest(int requester) {
        if (!requesterList.Contains(requester)) {
            requesterList.Add(requester);
            Refresh();
            #if DEBUG
            RefreshObjectLists();
            #endif
        }
        
    }
    public void RemoveRequest(int requester) {
        if (requesterList.Remove(requester)){
            Refresh();
            #if DEBUG
            RefreshObjectLists();
            #endif
        }
        
    }
    public bool GetStatus() {
        return currentStatus;
    }
    void Refresh() {
        if (requesterList.Count > 0) {
            if (!currentStatus) {
                onActivated?.Invoke();
                onStatusChanged.Invoke(true);
                currentStatus = true;
            }
        } else {
            if (currentStatus) {
                onDeactivated?.Invoke();
                onStatusChanged.Invoke(false);
                currentStatus = false;
            }
        }
    }
drowsy totem
#

is this your approach?

  1. you have a list of integers
  2. some integers are IDs of things and others are not
  3. you want to check if an integer matches the ID of a thing, and if so, you do an action?

what happens is the integer on the list randomly happens to match an ID, but wasn't an ID, just a randomly matching number?

lean basin
drowsy totem
gaunt ice
#

there is chance of false positive so you need to split the list, if it doesnt matter then keep your work

timber tide
#

id' just sync to system time every so often

rare basin
#
        foreach (int id in yourList)
        {
            Object obj = EditorUtility.InstanceIDToObject(id);
            if (obj != null)
            {
                // The integer is a valid InstanceID, and obj is the corresponding object
                Debug.Log($"InstanceID {id} belongs to {obj.GetType().Name} component");
            }
            else
            {
                // The integer is not a valid InstanceID
                Debug.Log($"Integer {id} does not correspond to any InstanceID");
            }
        }
lean basin
rare basin
#

then what else do you need

drowsy totem
#

@lean basin
if you add cs at the end of the first three backticks you get colour information btw
```cs
some code
```

lean basin
rare basin
#

if(obj is MonoBehaviour)

lean basin
rare basin
#

if Dog inherits from Animal

#

is dog still a animal?

lean basin
#

im pretty sure I tried that before and it returned false. Let me try again

gaunt ice
#
public class HelloWorld{
    public class A{}
    public class B:A{}
    public static void Main(string[] args){
        B b=new();
        Console.WriteLine (b is A);
    }
}
#

try it

drowsy totem
#

there's IsSubclassOf , which might be what you want. is MonoBehaviour might work too, I haven't tried it myself, but a quick google search implied it might not work in all cases

languid spire
#

is or as will work, is returns true/false, as return class or null, use either. is is more efficient if you dont actually need the cast

lean basin
#

Oh it works!! thanks everyone

My bad, looks like I actually haven't tried that before. Instead of is I used as then compare null. And I mistakenly thought I already used is.

daring island
#

How to force resolution to be the same in the build as in the editor? For example, i have 1440x3088 and when builded it shows all unplayable area of the game, which are out of the camera in the editor.

sleek radish
#

Get world position of object as a child

drowsy totem
daring island
#

@drowsy totemaspect ratio

#

Well it should be as in a mobile, but i want it to be that way on PC either

#

With black bars or whatever

#

It makes it this way, when i want to constrict view camera to the width of this bottom line

#

And in the editor the camera set exactly like that

#

But not in the build

drowsy totem
#

Basically, they edit the values of the Camera object to enforce a specific aspect ratio

daring island
#

@drowsy totem brilliant. That's why i needed. Thank you

shell oriole
#

Hello! I need some help. I am making a choose your own adventure game in Unity. Should I use scenes for every new choice?

keen dew
#

no

shell oriole
#

so what should i do?

wintry quarry
#

Look into Ink for example

#

Or NaniNovel

shell oriole
#

Well, the problem is that my text adventure game is not quite standard. And plus I've already programmed a choice system.

swift crag
#

i would suggest looking into one of these existing systems and seeing if you can adapt your idea to work with them

shell oriole
#

It's a life simulator that is fully randomized.

#

I'm just not sure how it would work.

#

What I'm asking is just, what should I use scenes for, and what I should not use them for.

drowsy totem
#

scenes are, among other things, containers of data that takes a while to load

#

you make choices quickly, and want the responses to be quick

#

you don't want to be loading and unloading data all the time, so you shouldn't change the scenes too often

shell oriole
#

The idea of the game is that it gives you an event in your life, and then you respond by choosing

drowsy totem
#

yes, that is pretty typical for a choose your own adventure game

shell oriole
#

but it skips a month every turn

drowsy totem
#

it's pretty typical for turn based games to have a turn counter

#

whether turns are days, months or hours, it's just a number going up

shell oriole
#

yes, but what should I do for it?

drowsy totem
#

which text game / CYOA tutorials for unity have you watched, or which games in the genre have you analyzed from a technical perspective?

#

I haven't done any of those in Unity, so I don't know the best practices, but I assume there will be resources out there

shell oriole
#

Just I don't want to load a scene for every new event

#

so what should I do? Just change the text?

drowsy totem
#

you'd want to have an event manager

#

that's separate from your UI

#

let's say you have an event UI

#

it shows the typical CYOA stuff - text description, visuals, choices, perhaps some stats and other info

#

you have a separate set of data that includes each possible event

#

each event knows its texts, visuals, choices etc

#

you have some sort of an event manager that reads the info from the chosen event, and uses it to set up the event UI with the correct stuff

shell oriole
#

Alright.

drowsy totem
#

and when you make a choice, it displays whatever the event needs displayed, and changes the stats and other info as necessary

#

a scene would be necessary if there's a need to change the UI in a major way

shell oriole
#

Ok. Thank you!

drowsy totem
#

say, moving between life stages, where the information available and events available need changing

shell oriole
#

Yeah.

#

ty!

drowsy totem
#

just so you know, there's a bunch of game engines specifically for CYOA games, text adventures and visual novels, and one of those might make your game idea easier to implement than Unity

#

you can absolutely do it in Unity too, and it can be a good way to learn, so it depends on how much your goal is "make the game", and how much it is "learn new stuff"

shell oriole
#

Ok, I will note that. Thank you!

dim halo
#

how can I perfectly allign to objects in unity

unique hull
dim halo
#

these two objects arent perfectly alligned

#

as you can see there is a little gap

#

I want them to be perfectly alligned

silk night
unique hull
#

this
As they are rectangular , you can calculate it by using half of the width/height to determine the x/y coordinates

icy junco
#

how can i add like a character and movement animation into my game is the only way just making it all myself or is there like a way to just import it

rare basin
bold nova
#

Trying to calculate for input duration (how long player has pressed button) , any idea why i get negative numbers? xDir and YDir are fields of the movement class

private void Move()
{
    xDir = Input.GetAxis(horizontalAxis);
    yDir = Input.GetAxis(verticalAxis);
   
    Vector3 moveDir = new Vector3(xDir, yDir);

    transform.Translate(moveDir * movementSpeed * Time.deltaTime);
}

private void CheckInputDuration()
{
    if (Input.GetButtonDown(verticalAxis) || Input.GetButtonDown(horizontalAxis))
    {
        startMoveTime = Time.time;
        Debug.Log("Start = " + startMoveTime);
    }

    if (Input.GetButtonUp(verticalAxis) || Input.GetButtonUp(horizontalAxis))
    {
        endMoveTime = Time.time;
        Debug.Log("End = " + endMoveTime);
    }
    float time = endMoveTime - startMoveTime;

    TimeSpendMoving += time;
    Debug.Log("Time moved = " + TimeSpendMoving);
}
buoyant knot
buoyant knot
#

also get button up for an axis is wacky

swift crag
#

You're starting the timer whenever either the vertical or horizontal axis goes "down"

#

I guess that'll happen when the axis goes from 0 to non-zero?

#

Then you stop when either axis goes "up"

#

and then you're constantly adding endMoveTime - startMoveTime to TimeSpendMoving

#

which makes no sense; that's adding the duration to the total every frame

#

this is doing all kinds of wacky things

#

here's how I would handle this

#
Vector3 moveDir = new Vector3(xDir, yDir);

bool moveHappening = moveDir.magnitude > 0.01f; // some small value

if (moveHappening) { 
  timeSpentMoving += Time.deltaTime;
}

if (!currentlyMoving && moveHappening) {
  startTime = Time.time;
} else if (currentlyMoving && !moveHappening) {
  endTime = Time.time;

  float duration = endTime - startTime;
  // do something with the duration here
}

currentlyMoving = moveHappening;
#

this will add to timeSpentMoving every frame that you're moving around

#

it will also record when you start and stop moving

bold nova
swift crag
#

np!

queen adder
#

I'm making a fighting game and want the name of the character appear on a textbox when the mouse hovers over them by reading their profile image. here's my script:

#

code

#
//public class ChooseLeaderButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    [Header("Elements of Faction")]
    public TMP_Text chooseText;
    [Header("Elements of Leader")]
    public Image imageOfLeader;
    string nameOfLeader;
    string currentLeaderName;
    public void OnPointerEnter(PointerEventData eventData)
    {       
        nameOfLeader = imageOfLeader.sprite.name;
        currentLeaderName = nameOfLeader.Replace("ChoicePic", "");
        chooseText.text = currentLeaderName;
        Debug.Log(currentLeaderName);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        chooseText.text = "Choose Your Character";
    }
}```
eternal falconBOT
swift crag
#

it's the grave: the lowercase tilde

#

what a `grave situation!`

buoyant minnow
#

bottom ones as well at the closing side

#

and u need 3 of them

#

and a linebreak. u have a comment at the start

queen adder
#
public class ChooseLeaderButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    [Header("Elements of Faction")]
    public TMP_Text chooseText;
    [Header("Elements of Leader")]
    public Image imageOfLeader;
    string nameOfLeader;
    string currentLeaderName;
    public void OnPointerEnter(PointerEventData eventData)
    {       
        nameOfLeader = imageOfLeader.sprite.name;
        currentLeaderName = nameOfLeader.Replace("ChoicePic", "");
        chooseText.text = currentLeaderName;
        Debug.Log(currentLeaderName);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        chooseText.text = "Choose Your Character";
    }
}```
#

like this?

buoyant minnow
#

yes but is ur class commented out on purpose?

queen adder
#

no, I just put it wrong

buoyant minnow
#

haha okay whats the issue with the code

queen adder
#

now

#

I want the name of the character the player is going to select to appear on a textbox when the mouse hovers over the image/button of the character. the console says I read the name fine but the text in the textbox doesn't change

rare basin
#

are you changing the value of a text property of the texxt mesh pro related to the textbox?

queen adder
#

textmeshpro

polar acorn
#

Is it an InputField or just a normal text object?

queen adder
#

a normal text object

#

the textbox just allow the player to read the name to know who they are choosing

polar acorn
#

Seems like one of two possibilities:

  1. Something else is changing the text back after this sets it to currentLeaderName
  2. The text getting changed in code is different than the one you think it is
#

I think 1 is more likely, it's possible a different object's PointerExit is being run after this object's PointerEnter

#

And overwriting it back to default text

queen adder
#

but wouldn't OnPointExit just change the text to "choose your character"? the text is just empty

polar acorn
#

How are you assigning chooseText? Is it a prefab, or an object in the scene?

queen adder
#

an object in scene

polar acorn
#

And that object is directly dragged in to each instance of this class?

queen adder
#

just found in a different script that the choose text is chooseText.color = textTransparent;

#

that seems to be my problem

polar acorn
# queen adder yes

Yeah so it's definitely another script overwriting the text, which it seems like you found

queen adder
#

thanks for the help anyway

queen adder
split dragon
#

Hi. I decided to make a more "realistic" flashlight. I want the flashlight to keep up with the camera's rotation speed. I wrote a line (29) for this. The flashlight lags behind the camera, but it lags too far behind. What else do I need to add?

swift crag
#

is the lantern parented to the player?

#

if so, this code doesn't really make senes; it's going to set the local rotation of the lantern based on this frame's mouse moverment

wintry quarry
#

anyway - make the light a child of the camera

split dragon
#

Script on the Camera

open apex
#

I am watching a coding tutorial and the person uses "snap settings" I can't find any snap setting on my version of unity

#

does anyone know where to find them?

open apex
#

thanks

sage mirage
#

Hey, guys! For one reason, when my game is Game Over I still can interact with the pause button. I was thinking how to fix it I have tried everything.

#

Here is the code:

 {
     if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == true)
     {
         if (gameIsOver == false)
         {
             StartCoroutine(ResumeAfterDelay());
         }

         else if (gameIsOver == true)
         {
             gameIsOver = true;
         }
         
     }

     else if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == false)
     {
         if (gameIsOver == false)
         {
             StartCoroutine(PauseAfterDelay());
         }

         else if (gameIsOver == true)
         {
             gameIsOver = true;
         }
         
     }
 }```
wintry quarry
sage mirage
#

I am not sure I just got confused

sage mirage
wintry quarry
#

also why do:

if (gameIsOver == false) {
  ...
}
else if (gameIsOver == true) {

}```
You can just do:
```cs
if (gameIsOver) {

}
else {

}```
wintry quarry
#

Or are you talking about the escape keyboard button

sage mirage
keen dew
#
else if (gameIsOver == true)
{
   gameIsOver = true;
}
#

🤔

wintry quarry
#

yeah that makes no sense lol

sage mirage
#

I know XD

#

I just didn't know what else to write XD

wintry quarry
#

You need to explain what this code is supposed to be doing and where/when/how it runs

ivory bobcat
wintry quarry
#

Is this code being called from Update somewhere? From a UI bitton handler?

sage mirage
#

Anyway, I have a button that enables and disables the pause menu screen which for my game is a gameobject

wintry quarry
sage mirage
#

I am using escape button

wintry quarry
#

ok so is this code in Update?

sage mirage
#

yeah

wintry quarry
#

ok so - cs else if (gameIsOver == true) { gameIsOver = true; }

#

this does absolutely nothing

#

I don't understand why it's here or what you expect it to do

sage mirage
#

I have something like this now

wintry quarry
#

if you don't want to be able to pause when the game is over then I would expect something like:

if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive && !gameIsOver)```
sage mirage
#
 {
     
 }

 else if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == false)
 {
     
 }```
#

I have to put coroutines inside of them

wintry quarry
#

what's wrong with just else?

#

Why do you retype the whole thing

sage mirage
#

Don't worry about that I am just capricious

wintry quarry
#

void Update() {
  if (gameIsOver) return; // skip everything
  
  if (Input.GetKeyDown(KeyCode.Escape)) {
    if (pauseIsActive) {
      // unpause
    }
    else {
      // pause
    }
  }
}``` This is how I'd do it
sage mirage
ivory bobcat
#

If you can pause and unpause, we can assume game over isn't ever true.

wintry quarry
#

return means to exit the function immediately

sage mirage
#

yeah ok

wintry quarry
#

since the function has void as the return type, we don't need to return an object. We can just return; on its own

sage mirage
#

ok

#

@wintry quarry Hey! So, whenever I want to exit a function completely I have to use return right? I just didn't know what to put on the else statement after the if condition.

#

Like if I don't want to do something else I can exit with that keyword?

wintry quarry
wintry quarry
sage mirage
wintry quarry
#

just delete the whole else entirely

#

what's the point of it

wintry quarry
edgy fox
#

how do I compare the rotation of 2 objects around only one axis? I tried just comparing their transform.rotation.EulerAngles.y but then when one would snap from 179 to -179 the code breaks

edgy fox
#

so is there a function to compare the angle just around aroudn an axis rather than just total difference if that makes sense

#

ah ok thans

wintry quarry
#

so for example:

float angle = Vector3.SignedAngle(objectA.forward, objectB.forward, Vector3.up);```
edgy fox
#

should that minus be an =?

wintry quarry
#

yes

edgy fox
#

the second is from top - would your code discriminate between the two or would it just return the total angle

#

because one of the objects' gameObject.forward is pointing down and to the right

#

comparing camera to the walls of that frame

wintry quarry
#

the vectors will be projected on the plane of the provided axis

#

and then the angle will be calculated

#

so it's fine

edgy fox
#

ah ok awesome

west sonnet
#

How can I play multiple audio clips from the same object? Right now, I have 2 audio clips that each have their own audio source on an object, but if they play at the same time, it messes up the audio

west sonnet
polar acorn
west sonnet
#

The argument, would be the name of the audioclip, right?

wintry quarry
#

no

#

it would be a reference to the audio clip you want to play

polar acorn
west sonnet
#

Not sure what I'm doing wrong here

wintry quarry
#

it wants an audio clip

west sonnet
#

Oh, I see 🤦🏻‍♂️

wintry quarry
#

Basically you tried to put a CD Player inside your CD Player, instead of the CD

silver sun
edgy fox
polar acorn
wintry quarry
polar acorn
edgy fox
wintry quarry
#

What are you trying to do exactly?

#

Why didn't you try the SignedAngle approach I recommended before?

polar acorn
wintry quarry
#

subtracting direction vectors isn't going to give you anything particularly useful

swift crag
#

use the methods that Unity generously provides you

#

they're great

edgy fox
west sonnet
#

When using PlayOneShot(), I only have to have 1 AudioSource, right? Or do I need one for each clip?

wintry quarry
#

Why not follow my example instead?

edgy fox
#

oh I'm a bozo

swift crag
wintry quarry
#

if you just want to know if the objects are facing roughly the same direciton on the y axis you could do this:

// project both vectors on the x/z plane:
Vector3 objectForward = Vector3.ProjectOnPlane(wallGrandParent.forward, Vector3.up);
Vector3 camForward = Vector3.ProjectOnPlane(transform.forward, Vector3.up);
float angle = Vector3.Angle(objectFoward, camForward);
if (angle < 90) {
  // they're facing sorta the same way
}
else {
  // they're facing sorta opposite ways
}```
swift crag
#

However, if you change the audio source's pitch, the pitch of all of the playing clips will change, iirc

polar acorn
west sonnet
#

Ahh okay

swift crag
#

Yes.

cosmic quail
west sonnet
#

Hmmm, I hadn't thought about that. That could be a good idea, thanks

deft siren
#

is there a way to make it so th Ai monster keep facing the direction theyre going?

#

like, without going off the trail/cutting sharp edges

gritty stratus
# west sonnet Not sure what I'm doing wrong here

Idk if you'd even want to touch this, but FMOD is fantastic for audio handling if you want to get a bit more in depth into dealing with audio. However, it is a bit of a learning curve. Personally, I like it better than the standard Unity way of calling audio; but everyone differs

ivory bobcat
swift crag
deft siren
swift crag
#

It's doing exactly what you told it to

wintry quarry
swift crag
#

It's finding a path towards the destination inside the navmesh

#

yes, if you want the entity to move on a grid, you need to make it move on a grid

west sonnet
#

So, I've tried making an audiomanager object that has an audiosource attached to it. But now when I play, I get this error and no sound

#

This is my code. Am I doing something wrong?

swift crag
#

well, where's the error coming from?

deft siren
#

i disabled this and im going to test if it works

swift crag
#

it's absolutely not coming from the line you have highlighted in the code editor

swift crag
deft siren
#

damm

swift crag
#

OffMeshLinks are explicitly placed to create a "bridge" across an otherwise unwalkable gap

ivory bobcat
ivory bobcat
#

Also, post the !code more appropriately so we can see the line numbers

eternal falconBOT
wintry quarry
west sonnet
#

I'm not sure I know what you mean

wintry quarry
#

was null

#

Did you assign your audio clips?

west sonnet
#

But it's an audio clip?

#

Yeah

#

In the inspector

wintry quarry
#

it seems loike you didn't

west sonnet
#

Here on the right

wintry quarry
#

what object do you have selected there?

west sonnet
#

The gun

#

Not the audiomanager

short hazel
#

It's that weird error, the AudioSource is null, not the clip

#

Deep down it calls an extern static method with the source and the clip, and the error says that source is null

west sonnet
short hazel
#

No you should make sure what you call PlayOneShot(clip) on is properly referenced in your Inspector

ivory bobcat
#
Debug.Log($"{name} played the one shot: '{GunShotReloadSound}'", this);```
short hazel
#

All the properties here in your inspector are in bold, and show a blue margin on the left. This means the change hasn't been applied to the original prefab.
Any instantiations of the prefab won't have the source referenced

ivory bobcat
#

Click the log message and make sure everything is appropriately referenced in the inspector.

#

The object should become highlighted yellow when the message is selected.

west sonnet
#

if I double click the error, it does this

ivory bobcat
polar acorn
#

Also log AudioManager just to be sure

ivory bobcat
west sonnet
ivory bobcat
#

This would be at runtime as you're assigning it in Start.

ivory bobcat
polar acorn
# west sonnet This is what I get

I believe we ran into this somewhat recently, since PlayOneShot is an extension method rather than actually on AudioSource, it gives the "null parameter" error instead of a normal NullReferenceException. Log AudioManager as well

west sonnet
#

It looks like my Audio Manager reference on the right was set to none when I start the game

#

but in editing mode, It's set as my audio manager

polar acorn
ivory bobcat
#

Get component in Start needs to be removed

west sonnet
#

I need to remove get component from start?

#

It worked but now if I shoot, I get this really horrible sound. It's meant to be a gun shot, then a reload sound

polar acorn
west sonnet
polar acorn
#

Meaning you set AudioManager to null

west sonnet
#

ahh okay

#

Should I add a script to the AudioManager with GetComponent?

polar acorn
#

Why

celest citrus
#

I am completely new to coding trying to make an FPS and currently completely copying code from yt, but when i go into unity i get an error, does anyone know what i did wrong?

nimble hinge
#

woah so many people

ivory bobcat
west sonnet
celest citrus
nimble hinge
slender nymph
eternal falconBOT
nimble hinge
#

you see these functions?

polar acorn
eternal falconBOT
nimble hinge
#

add semicolon at the end of them

ivory bobcat
west sonnet
nimble hinge
celest citrus
#

ohh ty

nimble hinge
#

it should look like this

west sonnet
#

Thank you haha

celest citrus
#

im not getting any errors rn

polar acorn
ivory bobcat
#

Follow the guide and tell us where you get stuck. Ideally, you wouldn't reinstall but run the launcher and ensure the work loads and whatnot are correct.

#

Running the installer again will not reinstall but rather modify the current installation

rocky canyon
#

Tools > Get Tools and Features >

  • select unity

  • click modify in bottom right to install..

  • in unity go to Edit > Preferences > External Tools and Select it

  • Remember that Restarts can help edge the computer along.. if things dont show up / missing

west sonnet
#

Is there a way to freeze the player? I want the player to freeze when dying, right now if the player is moving and dies, the player loses control but keeps moving in the direction they were moving in

rocky canyon
#

disable the scripts that make it move

west sonnet
#

Ooooooh good idea!

rocky canyon
#

if its a rigidbody may have to zero out its velocity and then disable

bitter tapir
#

I installed Cinematic Studio Unity and I can't add a sequence to the project. It just isn't there

west sonnet
rocky canyon
#

rigidbodyReference.velocity = Vector3.zero;

#

movementScript.enabled = false;

west sonnet
# rocky canyon movementScript.enabled = false;

My movement script is called PlayerMovement. I tried doing PlayerMovement.enabled = false , but it didn't work for me. So I'm trying gameObject.GetComponent<PlayerMovement>().enabled= false;

swift crag
#

PlayerMovement is a class.

#

PlayerMovement.enabled is trying to find a static member of the class named enabled

#

No such member exists, so you get an error

#

enabled is stored on specific instances of PlayerMovement

swift crag
#

you ask Unity to find a PlayerMovement on your game object

swift crag
#

then you set the enabled field to false

#

This will cause an error if GetComponent<PlayerMovement>() can't find a PlayerMovement, however.

west sonnet
#

So if I understand correctly, to do PlayerMovement.enabled = false, I'd have to reference it first?

swift crag
#

You'd need to have a reference to a specific PlayerMovement

edgy fox
# wintry quarry show code
if (ArrayDict.wallList.Count > 0) {
    foreach (GameObject wall in ArrayDict.wallList)//wall holder parent - BlankNSEW - Check if it is within 180deg FOV of camera's rotation and if not don't render
    {
        Renderer wallRen = wall.GetComponent<Renderer>();
        Transform wallGrandParent = wall.transform.parent.transform.parent;
        float angleDiff = Vector3.SignedAngle(wallGrandParent.forward, transform.forward, Vector3.up);
        if (angleDiff > 0)
        {
            wallRen.enabled = false;
        }
        else
        {
            wallRen.enabled = true;
        }
    }
}```
swift crag
#
[SerializeField] PlayerMovement playerMovement; // assign it in the inspector

void Whatever() {
  playerMovement.enabled = false;
}
#

This is the ideal method.

#

Drag an object with PlayerMovement on it into the "Player Movement" field in the inspector

#

This will assign a reference to that specific PlayerMovement component

west sonnet
#

Right

west sonnet
swift crag
#

starting with the weakest reason: there's a performance benefit

#

GetComponent has to search the game object for a component of the type you ask for

#

this isn't trivial because you can ask for parent types

#

so GetComponent<Component>() will find some component

#

secondly: it makes your code easier to read

#

playerMovement.enabled = false; vs. GetComponent<PlayerMovement>().enabled = false

#

thirdly: it's more flexible. Your PlayerMovement component doesn't have to live on the same game object. you might wind up moving things around later.

#

I do still use GetComponent whenever I know the component has to live on the same object anyway

#

but I don't do it that often

#

and if I do, I do that in Awake, once

rocky canyon
swift crag
#

PlayerMovement.enabled = false; is trying to set a field on the class itself

#

which would work if enabled was static

#

but it's not!

rocky canyon
#

PlayerMovement myPlayerMovementReference;
myPlayerMovementReference = GetComponent<PlayerMovement>();
myPlayerMovementReference.enabled = false;

#

altho if u had public PlayerMovement myPlayerMovementReference; you could just assign it via hte inspector

#

but still.. dont try to disable the Script, instead disable a reference of an instance of that script

swift crag
#

in case you are unclear about why I used [SerializeField] and spawncamp used public

rocky canyon
#

lots of text we just sent

#

😄

swift crag
#

serialized fields appear in the inspector.

#

by default, public fields get serialized, and non-public fields do not

#

you can use [SerializeField] to tell Unity you want to serialize a non-public field

rocky canyon
swift crag
#

For anything that's only going to be used by the class itself, private is the ideal access modifier

west sonnet
#

What's the difference between public and [SerializeField] ? I've mostly been using public whenever I want to assign something in the inspector

swift crag
#

It also happens to be the default.

rocky canyon
#

public means u can access it from any script

#

if u use serialized private.. you can still see in the inspector..

swift crag
#

A public member is visible to every class.

west sonnet
#

but with SerializeField, you cant?

rocky canyon
#

BUT other scripts wont be able to access it

swift crag
#

A private member is only visible to the declaring class.

west sonnet
#

Oooooh

rocky canyon
#

if its a private SerializedField

swift crag
#

(or struct. i forget the proper name for "class or struct")

#

The type or member can be accessed only by code in the same class or struct

#

Ah. There is none!

#

If you're just starting out, don't sweat it too much.

rocky canyon
#

private serialized are good for stuff like you want to do..
you really need a reference to the script ur working in.. but you dont necessarily need it public for everything..

#

so just drop in teh reference in the inspector.. and u dont need to use any getcomponenet calls or anything

swift crag
#

Access modifiers are nice to get right when you're writing code for just yourself, since it's easier to reason about your code when there are fewer ways for A to mess with B

#

They're vital if you're writing code that other people use. Once people depend on some non-private member, changing it can break their code.

#

Note that "other people" includes "you from six months ago"

#

dear Fen: what the hell were you thinking

rocky canyon
#

i dont associate with my past tense self..

#

he's usually clueless 😅

west sonnet
#

Wait, but the script that I'm disabling is the same script I'm writing the disable code into, so would I still have to do the same process?

#

Because I'm not disabling a different script

rocky canyon
#

its fine.. but think about what u want

swift crag
rocky canyon
#

if u disable it.. thats it.. its done

#

no more code from that script is gonna work

swift crag
#

The access modifier on the field affects who can see the field

rocky canyon
#

unless u enable it from another script

swift crag
#
public class Foo {
  [SerializeField] private Bar bar;
}
#

only Foo can see that bar field

west sonnet
#

That's fine, I'm disabling it when the player dies anyway. Then it gets reenabled when the player respawns

rocky canyon
#

👍

#

sounds good then

swift crag
#
public class Bar : MonoBehaviour {
  public void Huh(Foo foo) {
    foo.bar = this; // compile error
  }
}
rocky canyon
#

Huh?

swift crag
#

clarifying what the access modifier means

rocky canyon
#

i know.. bad joke. my drumset player wasn't around to do the "badum tiss"

swift crag
#

oh, I thought that might be the case :p

rocky canyon
#

hes fired

#

okay, imma call today "Progress Monday"

#

and let it wash across my project.. maybe something productive will happen

#

I think imma work on my pathfinding stuff.. I want to click and hold on a unit.. then this allows me to draw on the ground.. as I draw waypoints will be generated every X amount of movement..

#

when i release the waypoints all get added into the navigation setup

#

THEN idk.. b/c the navmesh agent is gonna ignore the lines i drew

#

the only thing i can think of to compensate is to add many waypoints... but then the movement will probably look unnatural.

warm condor
#

hey, so I have a problem with the RigidBody2D physics system when I want to slide right when I hit the ground, the horizontal velocity that I am setting isn't very consistent depending on the angle of which I am hitting. Here I drew a picture to show you what I mean:

#

What I want to to have a consistent speed when sliding and hitting the ground no matter what way the player does it. So how do I fix this?

stuck palm
#

is there a random float generator instead of int?

swift crag
#

Random.Range will produce floats if you give it floats.

stuck palm
#

why isnt this working?

swift crag
#

look at your first error

#

on the first line in that screenshot

stuck palm
swift crag
#

your method has no body.

#

now, it might look like it has one

stuck palm
#

OHH

swift crag
#

but there's something at the end of the first line..

stuck palm
#

the semicolon

#

im blind thanks 😭

rocky canyon
#

someone should start a freelance "second eyes" type service

swift crag
#

It's not a syntax error, but it is semantically bogus here

#

two of my favorite words, "semantically" and "bogus", right in a row!

stuck palm
#

why would the error not come by the semicolon?

#

why would it let me do it if it was abstract or extern

swift crag
#

It's valid to write a method without a body in some contexts.

#

like if the method is abstract

#

An abstract method can only be declared inside an abstract class.

#

Any non-abstract class that inherits from the abstract class must override the method.

stuck palm
#

right

#

awesome, thanks

swift crag
#

In that case, the abstract method must be declared without a body

#

You also do this inside of an interface

#

iirc every method in an interface is implicitly abstract

#

(or something close to that)

#

That's why the error wasn't on the semicolon. It's not really the semicolon that's wrong here

#

What's wrong is that your non-abstract method doesn't declare a body

#

(also, an extern method is one that's actually defined somewhere else. I haven't used that keyword in C# yet)

celest citrus
#

my character is moving without the camera how do i fix it

#

nvm i fixed it lol

stuck palm
#

why is it still spawning things after one spawns?

polar acorn
stuck palm
#

patient i mean

polar acorn
# stuck palm spawns a player

So, let's work through this line by line.
You start, transform.childCount is presumably 0, and playerSpawned is false.
This means the first if statement occurs and playerSpawned is set to true, and the coroutine is started.
The coroutine reaches a pause.
End of fixed update.

Next fixed update, transform.childCount is still 0, and playerSpawned is true.
This does not satisfy the if condition, so we move to the else block.
playerSpawned is set to false.
End of fixed update.

Next fixed update, transform.childCount is still 0, and playerSpawned is false.
This means the first if statement occurs and playerSpawned is set to true, and the coroutine is started.
The coroutine reaches a pause.
End of fixed update.

Repeat the above blocks until the first coroutine's timer is up, and transform.childCount becomes 1. All other coroutines who have started since then are still running, and will spawn another object

rocky canyon
#

great synopsis

#

these kinds of bugs are terrible to find on ur own.

toxic sun
#

Guys. I'm don't understand why raycast don't work there. This function calls from above and should return collider of selected object

rocky canyon
#

the only method i know of that helps is using debugging tools and breakpoints to step thru the code

rocky canyon
#

or just walking thru it like digiholic just did

toxic sun
timber tide
#

ya need colliders rather wrong raycast type

wintry quarry
#

MeshCollider is a 3D collider

#

Make sure you only use 2D colliders with 2D physics queries

rocky canyon
#

while we're here.. this override thing doesn't have to be assigned does it? like include layers say Nothing.. but it'll still work like it should w/o having those selected eh?

toxic sun
#

like box collider 2d?

wintry quarry
#

any 2D collider

timber tide
#

oh right you're using 3D with 2D raycast

#

if you're going 3D, yeah wrong raycast

toxic sun
#

thanks wm!

timber tide
#

also for spheres/circles you can just use primitive colliders

rocky canyon
#

primitive colliders are cheap.. i try to use em as often as possible..

honest haven
#

Hi my code works, i can pause the player at any moment and the animation pauses and then restarts where it left of. My player also does not move while im attacking. But im a bit unsure if im over complication the code. https://gdl.space/yuvesohuza.cs does it seem a bit hacky?

rich adder
honest haven
#

cool thanks just worried about the two returns in the update

rich adder
#

nothing wrong with having return in Update, pretty normal

honest haven
#

cool thanks for your advice

swift crag
#

I occasionally footgun myself with that

#

it goes like this

#
  • code that always runs
  • code that only runs sometimes

I decide an early-return between the two makes sense

Then I forget that I did that and add some more code at the end!

honest haven
#

lol

swift crag
#

e.g. I have a "helpless" flag on entities that get set when they're unable to act; I exited Update early in that case

honest haven
#

yes i can understand why

swift crag
#

then I forgot I did that...

honest haven
#

i just created a bool in my game manager for pause. then i set it in my menu to toggle on and off. then i did the same in another class and wondered why it dont work. its cuz i set it false some where else. So now going to add two functions in my game menu and just add every thing that needs to be paused there and call the meathod instead

rich adder
#

could make an Interface for each object that needs to like pause, then listen for event

#

IPausable or something

honest haven
#

ohhh dont no about listen events is that easy to set up

rich adder
#

events are quite powerful and pretty easy to get into imo

honest haven
#

thanks ill take a look

rocky canyon
#

Unity Events are awesome..

#

if(condition) -> InvokeEvent

#

then u can pretty much do anything within the event

honest haven
#

yh think ill do that route

rich adder
#

def eleminites a lot of polling for stuff in Update

rocky canyon
#

i wrote my own event system..
uses an Action class
i drop it on my gameobject and its set up to do different functions
like trigger it when the gameobject spawns in, or an option for a delay, or mouse click

#

just some generic stuff.. then i have others with a list of actions and i can just stack em in there.. and it'll loop thru the actions invoking them 👍 pretty neat setup

honest haven
#

That sounds amazing.

#

Does it end up making you think what else can i add to it, when it prob doesnt need it

rocky canyon
#
public class Action : MonoBehaviour
{
    [Tooltip("Uses Start Method When False")]
    public bool onEnable;
    public UnityEvent ActionEvent;

    private void Start()
    {
        if(!onEnable)
        {
            ActionEvent.Invoke();
        }
    }

    private void OnEnable()
    {
        if(onEnable)
        {
            ActionEvent.Invoke();
        }
    }
}
#

lol.. yea i have that problem anyway

honest haven
#

lol think ill end up doing that too

rocky canyon
#

i have trouble knowing when enough is enough

#

its so easy to fixate on a certain system or mechanic and build it more elaborate than u actually need

#

i usually just package it up at that point.. and have a package i can pull in and modify the things i dont need

honest haven
#

Yh so i was also fixated on statemachine and i ended up adding to somthing that prob dont need it. i saw i had it on my player and thought why not. Think thats when things get over complicated

rocky canyon
#

ya, nothing wrong with it tho.. if ur a beginner and you're learning its great to experiment

honest haven
#

yh thats it

rocky canyon
#

even if u dont end up using it, atleast u went thru it, learned some stuff and exposed urself to new things

honest haven
#

100%

#

thanks for sharing

rocky canyon
#

np, lol see i dont even use it

#

i just have it

honest haven
#

lol

rocky canyon
queen adder
#

test.cs(26,13): error CS0103: The name 'ChangeTexture' does not exist in the current context

I've been trying for a few days and I can't
I don't know why I get that error that this objective does not exist

frigid sequoia
#

How coud I check for a high concentration of a certain type of object in screen?, like, a proyectile that automatically search for a high concentration of enemies to maximize damage

queen adder
polar acorn
eternal falconBOT
rocky canyon
#

its actually a material change if i remember ur issue correctly

#

Some sort of renderer . material = new material

#

the error seems to imply you dont have a function called that..

#

go ahead and share ur script ^

queen adder
#

ok

rocky canyon
#

ChangeTexture or ChangeMaterial which is more likely what u want... are not built in functions or anything.. ud have to create the method and then call it

stuck palm
#

is ondestroy called before or after destruction?

edgy fox
#

I want a function that will output a bool if my camera is in front or if it is behind the wall - I've been messing around with Vector3.SignedAngles for a few hours but either my math is terrible or it's the wrong way of approaching the problem

#

and I'm pretty sure wallGrandParent.forward is the wrong variable to be using because all walls output the same thing for it regardless of their rotation

cosmic dagger
edgy fox
#

(all 4 walls being logged there are facing a different cardinal direction)

#

I have found that when I do Vector3.SignedAngles(wallGrandParent.forward, transform.forward, Vector3.up, I do get an angle but then all walls read the exact same angle offset from the camera

rocky canyon
wintry quarry
#

look at the blue arrow in the scene view

#

which way is it facing

#

if they;re all facing the same way this is entirely the wrong approach

#

(make sure tool handle rotation is set to local)

cosmic dagger
edgy fox
#

nvm they're facing up

wintry quarry
edgy fox
#

I was in game view

wintry quarry
#

The blue arrow is transform.forward

edgy fox
#

ah, green is facing inwards which is up, would wallGrandParent.up work?

wintry quarry
#

try it

#

yes green is the up arrow

edgy fox
#

it's still reading 90 degrees

wintry quarry
#

what is

#

what does your code look like

edgy fox
#

nvm reassigned it later

queen adder
# rocky canyon Some sort of renderer . material = new material
public class test : MonoBehaviour
{
    private Vector3 lastPosition;
    private Material mat;
    private Material mat2;

    void Start()
    {
        lastPosition = transform.position;
    }

    void Update()
    {
        // Get the current position
        Vector3 currentPosition = transform.position;

        // Check if the position has changed
        if (currentPosition != lastPosition)
        {
            // Object is moving, change texture to movingMaterial
            mat = new Material(imagen1);
        }
        else
        {
            // Object is not moving, change texture to idleMaterial
            mat2 = new Material(imagen2);
        }

        // Update lastPosition for the next frame
        lastPosition = currentPosition;
#

not if I'm doing it right

edgy fox
rocky canyon
edgy fox
#
foreach (GameObject wall in ArrayDict.wallList)//wall holder parent - BlankNSEW - Check if it is within 180deg FOV of camera's rotation and if not don't render
{
    Renderer wallRen = wall.GetComponent<Renderer>();
    Transform wallGrandParent = wall.transform.parent.transform.parent;
    float angleDiff = Vector3.SignedAngle(wallGrandParent.up, transform.forward, Vector3.up);
    Debug.Log($"{wallGrandParent.up}, {transform.forward}, {angleDiff}, {Vector3.up}");
    if (angleDiff > 0)
    {
        wallRen.enabled = false;
    }
    else
    {
        wallRen.enabled = true;
    }
}```
rocky canyon
#

and besides that.. i thought you wanted to change the texture/material of something.. in ur code ur just setting materials. you're not using them anywhere

#

why not build ur materials like u need them.. and just swap the entire material?

edgy fox
#

I love Quaternion.AngleAxis

queen adder
polar acorn
#

I think first thing's first you should probably check the intro to C# guide in the pins and learn how code works. You can't just use a variable or function that doesn't exist, you have to define it

rocky canyon
#

instead of trying to copy the material, set the texture, re-assign it, etc

#
public class MaterialChanger : MonoBehaviour
{
    [SerializeField] private Material idleMaterial; // assigned in my inspector
    [SerializeField] private Material movingMaterial; // same

    [SerializeField] private MeshRenderer thisRenderer; // assigned in my inspector
    public bool flipMaterial; // public bool for testing

    void Update()
    {
        if(flipMaterial)
        {
            thisRenderer.material = idleMaterial;
        }
        else
        {
            thisRenderer.material = movingMaterial;
        }
    }
}
``` Sample Script, The MeshRenderer is assigned b/c thats what Renderers the material *on* the cube..
all I'm doing here is swapping the material it uses with the test boolean
#

same kind of thing can be done with every kind of renderer

ivory bobcat
#

The ternary alternative would becs thisRenderer.material = flipMaterial ? idleMaterial : movingMaterial;

rose galleon
#

where did I go wrong? I created a gameObject called Sword and assigned my inactive gameObject onto it, and made this:
void Attack()
{
if (Input.GetButtonDown("Fire3"))
{
Sword.SetActive(true);
}
}
But when I press leftshift it isnt activating

eternal falconBOT
polar acorn
#

But also, where do you call Attack and is left shift bound to Fire3?

queen adder
rose galleon
polar acorn
queen adder
wintry quarry
polar acorn
#

!code

eternal falconBOT
rose galleon
edgy fox
#

how do I change size via code?

ivory bobcat
#

You aren't calling attack anywhere

rocky canyon
rocky canyon
#

i understand what ur trying to do .. but the same thing applies to textures..

 [SerializeField] private Texture grassTexture; // assigned in my inspector
 [SerializeField] private Texture dirtTexture; // same

 [SerializeField] private MeshRenderer thisRenderer; // assigned in my inspector
 public bool flipMaterial; // public bool for testing

 void Update()
 {
     if(flipMaterial)
     {
         Material materialCopy = thisRenderer.material;
         materialCopy.mainTexture = grassTexture;
         thisRenderer.material = materialCopy;
     }
     else
     {
         Material materialCopy = thisRenderer.material;
         materialCopy.mainTexture = dirtTexture;
         thisRenderer.material = materialCopy;
     }
 }```
#

like here, you have to copy the material, Change its texture, and then use the COPY

edgy fox
#

ah orthographicSize

#

thanks

rose galleon
rocky canyon
#

it just matters what kind of renderer you're using and how the texture works w/ that renderer

queen adder
rocky canyon
#

thats even simpler then.. you just have to access the Image component and change the sprite

#

image doesn't use a texture

#

well it does use a TextureImage

queen adder
#

hmm, ok!

rocky canyon
#

not sure exactly how to do it with the Image component lol

#

i'll have to look it up

rose galleon
# rose galleon im so stupid

it is working now, I was just stupid, but another question.
The sword gameObject is a child object of the player object, and I made it so everytime the player touches the wall he goes back a scene, metroidvania style. However, the sword hitbox is triggering that, how do I stop it from doing that?

queen adder
ivory bobcat
#

Do you want the sword GameObject to not be able to trigger the change of scene?

rose galleon
night mural
ivory bobcat
summer pulsar
#

is there something wrong with my code ? i dont get why is it not working ?

polar acorn
night mural
summer pulsar
summer pulsar
polar acorn
night mural
#

they're there to help guide you

ivory bobcat
#

Don't put the method inside the other method.

rocky canyon
# queen adder Don't worry, if you don't get it, nothing happens 😅

you just have to assign the sprites.
```cs
[SerializeField] private Image thisImageComponent;

[SerializeField] private Sprite sprite1;
[SerializeField] private Sprite sprite2;

public bool changeSprite;

void Update()
{
    if(changeSprite)
    {
        thisImageComponent.sprite = sprite1;
    }
    else
    {
        thisImageComponent.sprite = sprite2;
    }
}```
queen adder
#

wow

rocky canyon
#

yea, it also has a .mainTexture which confused me for a bit

#

but if its an Image component you're probably most likely using sprites

stuck palm
#

why doesnt this work? i switched it from if component != null to if trygetcomponent and it doesnt work now

rose galleon
rocky canyon
#

those dont go inside the update loop

ivory bobcat
rocky canyon
#

new functions go outside the update or any other loop

summer pulsar
#

like this ?

rocky canyon
#

wait its a collision

#

like this

ivory bobcat
#

All those red curly braces

polar acorn
summer pulsar
queen adder
summer pulsar
rocky canyon
#

you have to assign it..

#

you just told the code there is an image component

#

you never told it which one it is

summer pulsar
#

ah

summer pulsar
rocky canyon
#

if its on teh same gameobject as the image component you can assign it in code,
like in the Awake() or Start() method..

thisImageComponent = GetComponent<Image>();

#

but since we used SerializedField (it exposes it in the inspector) so u can just drag it in

stuck palm
rocky canyon
#

if it were private.. (and you couldnt see it in the inspector) you'd have to assign it in code

#

the code within the tryget will only run if it successfully gets the component ur trying to get

deft siren
#

the AI isnt working and its giving me these errors but in the code theres none and the enemy has a nav

polar acorn
rocky canyon
rocky canyon
#

ur agent isn't on the navmesh

#

or just isnt

#

lol

polar acorn
# deft siren wdym?

I mean the thing this code is running on either:
A) Is not an Active Agent
B) Is not on a NavMesh

deft siren
#

the code is on mazeDog

#

as well as the mesh

swift crag
#

why is the navmesh surface on the dog?

polar acorn
deft siren
#

and it gets called right here on the code

deft siren
swift crag
deft siren
#

i mean the navmash lol

queen adder
# rocky canyon

The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?

I'm going to review little by little although I don't speak English very well and I use a translator 😖

swift crag
#

yes, I understand that you meant the navmesh

#

but having the navmesh on the mazeDog makes no sense

deft siren
#

why's that?

swift crag
#

did you read the documentation for what you're using at all

polar acorn
deft siren
#

i think we have a misunderstanding

deft siren
#

the mash and the dog

swift crag
#

Okay. The navmesh is not on the dog.

polar acorn
swift crag
#

You kept saying the navmesh was on the dog.

rocky canyon
#

you have to add the .UI using statement to be able to access the UI stuff in script

deft siren
#

well yet u guys know whats happening??

#

he simply doenst move

queen adder
deft siren
#

the code gives it a destination but still

rocky canyon
#

did you setup the NavMesh as well?

swift crag
deft siren
#

like baking the area?

polar acorn
#

Is the agent actually on the navmesh? And not hovering above it?

eternal needle
#

are the dog and the surface for the same agent type?

polar acorn
#

And are you sure you're referencing a NavMeshAgent in the scene and not a prefab?

deft siren
eternal needle
#

agents will try to automatically place themself on the navmesh, i dont think this would be the case

rocky canyon
#

unless its realy far away

polar acorn
eternal needle
#

🤔 interesting

deft siren
polar acorn
deft siren
#

the issue

rocky canyon
#

we can't assume much in here.. theres some crazy things people do

#

have to ask all the questions sometimes

ivory bobcat
#

Was the error resolved?

rocky canyon
#

screenshot the agent and its inspector

#

and screenshot the navmesh and its inspector

polar acorn
# deft siren the issue

Okay, so next is to make sure the agent you're referencing is the one you think you're referencing. While the game is running, check the object giving errors and click on the reference to the agent, does it highlight an object in the scene?

vernal minnow
#

how do i get an object to rotate without changing its x or y position?

ivory bobcat
polar acorn
ivory bobcat
#

Maybe you've got some other things you ought to share with us

vernal minnow
#

i currently have a player that uses tank controls and he either rotates across his front, or rotates just slightly off enough to be anoying

swift crag
#

sounds like your origin is bad

rocky canyon
#

yup, may need to fix up the origin, if its a model u can change it in a 3d software

queen adder
swift crag
#

If my player model is that cube, rotating the player will make the cube move around

rocky canyon
#

a bandaid fix is to use an empty container and position the tank where the center should be and rotate that instead

swift crag
#

(this cube is parented to an empty object)

vernal minnow
#

i honestly agree there bc the closest i could get to a fix with origin was left center causing the slight position change

vernal minnow
deft siren
rocky canyon
#

if its physics based it probably would.. ya

deft siren
#

wich by all means seems to be what mine is

rocky canyon
#

but if u use an empty container u move all ur rigidbody and stuff to the empty

swift crag
#

click on the error. see what object gets highlighted in the hierarchy.

vernal minnow
#

Im honestly not quite certain how to do it such that they wont separate when the empty objects collider hits another object

deft siren
swift crag
#

click once.

polar acorn
rocky canyon
deft siren
vernal minnow
queen adder
# rocky canyon

I have another question, so if I use with (lastposition) to detect motion and change the texture, is there something wrong with that system?

deft siren
#

all objects work as objects so i dont think thats it

polar acorn
# deft siren

Okay, and if you click on that object assigned to Ai while the game is running, does it highlight the one you think it is?

swift crag
ivory bobcat
swift crag
#

I triggered it and the console didn't take me anywhere

ivory bobcat
swift crag
#

Ah, you are right. My bad.

deft siren
# deft siren yep

the thing is i had the same code on a different monster and it worked just fine (the monster is disabled so it couldnt be interferring)

rocky canyon
polar acorn
# deft siren yep

On the line before one of the ones throwing the error, add this line:

Debug.Log($"{gameObject.name}'s ai agent is: {ai.gameObject.name}", this);

This will have the names in the log, and will highlight an object when you click on it (single click), since the error does not.

vernal minnow
rocky canyon
polar acorn
# deft siren 😭

Okay, when you click on it, does it highlight the one in the scene we've been looking at?

deft siren
#

yes

polar acorn
#

Hm... so it seems like this is the correct object, and it seems to be on a NavMesh...

nocturne parcel
#

Are static variables allowed to be serialized to JSON?

vernal minnow
#

transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z + (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10)); just to check, there isnt anything wrong with the actual rotation code right?

polar acorn
# deft siren yes

If you clear the console while the game is running, do the errors come back? Or are they one-and-done?

deft siren
#

they are repeating over and over

#

cause the code is trying to move it

ivory bobcat
#

This would imply that the script is on the maze dog object but what about the reference?

queen adder
polar acorn
#

Yeah, I just wanted to see if the issue might have been that it didn't start on the mesh but then moved onto it after the game started

polar acorn
ivory bobcat
#

Maybe have it highlight the ai instead

polar acorn
queen adder
queen adder
#

wow

eternal needle
queen adder
rocky canyon
#

i try to test everything that i help people with, so i know for sure it works

deft siren
queen adder
eternal needle
queen adder
#

So what exactly is the code to detect when it moves?😮

deft siren
eternal needle
queen adder
rocky canyon
#

it has a transform doesn't it?

deft siren
#

i guessed you meant the floor

eternal needle
#

a nav mesh surface

deft siren
#

like this?

queen adder
thorn holly
#

So I have a game with essentially a ton of very small events in which different things have to happen. Delegates would work well for these events, but aren’t really necessary. I can do individual work around for each one, but they would be pretty random and inconsistent case to case. Is using a ton of delegates better for consistency or should I do the smaller workarounds? I know someone mentioned that delegates create garbage and orphaned subscriptions. What’s an orphaned subscription and what can I do about it?

#

I asked something similar to this yesterday but I had to go before I could finish asking all my questions

deft siren
eternal needle
rocky canyon
#

if the transform.position is different on this frame, then it was on the last frame -> you have moved (are moving)
if the transform.position is the same on this frame as it was last frame, then -> you are not moving

  • In the script's Start method, create a variable to store the previous position. This variable will be used to compare with the current position in each frame.
    _previousPosition = transform.position; (a vector3) or (vector2 for 2d)
  • In the Update method, compare the current position with the previous position to check if the object has moved.
    if(transform.position == _previousPosition){// you havent moved}else{// you have moved};
  • set the new position as the previousPosition, so when the new frame happens it can compare again
    _previousPosition = transform.position;
deft siren
#

but the other monster still worked

eternal needle
# deft siren the mash and the dog

you have a surface, as shown by the blue floor thing here. Unless that is your actual floor.
But i suspect you never made one for the dog so it has no surface to walk on

#

you need to bake a surface for each agent type

deft siren
#

i strongly believe i already did that

eternal needle
#

You said you dont have any nav mesh surfaces, so i doubt you have

#

show me the surface then

thorn holly
deft siren
vernal minnow
#

I'm not sure how noticeable it is in the pictures but the camera movement when rotating is the current issue that im having 😅

deft siren
#

i baked it again to make sure and none was created

#

on any surface

eternal needle
# deft siren still none

i dont get how you claim you baked a surface for each agent type but you dont have a nav mesh surface. just make a nav mesh surface and this should be done then

deft siren
eternal needle
#

hm your navigation tab also does look quite different to mine, i dont have the Bake and Object tag 🤔 am i behind

queen adder
rocky canyon
eternal needle
rocky canyon
#

on ur surface mark it as Static and then in the Navigation window you just opened Bake it

deft siren
rocky canyon
#

with the navigation window open it should show the big blue mesh

deft siren
rocky canyon
#

🤔 interesting

deft siren
#

it was even moving a long time before but still with a shit ton of bugs

#

i really dont get why thats happening cause the old monster still works just fine 😭

#

ok so i figured something rlly interesting

#

changed back to the old agent type, humanoid

#

now its moving but all buggy like i said

#

gonna try to unbug this

rocky canyon
#

not sure what happens after that.. like when the event fires off..

#

Here are some potential issues:

Null Reference Exception:
If the event is fired after the object has been destroyed, attempting to invoke the event on a null reference (destroyed object) will result in a NullReferenceException.

Memory Leak:
The destroyed object, along with its associated event handler, will not be garbage collected as long as the delegate still holds a reference to it. This can lead to a memory leak.

To avoid these issues, it's good practice to always unsubscribe from events when the object is being destroyed. You can do this in the object's OnDestroy method or in a method explicitly designed for cleanup.``` this is what Chatgpt says about it.
deft siren
#

ok this one not much of a problem but, the dog is walking backwards, how do i make the navmesh know where the front is at

rocky canyon
#

rotate the graphics so it facing the right direction

#

ur graphics shouldn't be linked to ur main object anyway

deft siren
#

what graphics?

#

sorry if its dumb questions, im gonna start studying soon :(

rocky canyon
#

the dog is walking backwards

#

how do u know its backwards?

#

probably because the graphics look backwards.. thats the (graphics) im talkin about..

#

they should be a child of the navmesh.. u should be able to rotate them a full 180 degree's to make the dogs face, his butt

deft siren
#

like, the objects?

rocky canyon
#

and his butt, become his face

deft siren
#

it... still walks backwards

rocky canyon
#

rotating the graphics wont make the navmesh walk the wrong way

#

how?!

deft siren
#

i have no ideia

#

i tried rotating the navMash but then the model got all woogly

rocky canyon
#

rotating the graphics shouldnt change the way the navmesh walks..

#

the Purple is the Z axis (forward) its the Pawn (the navmesh) fowards direction

#

doesnt matter how i rotate the graphics.. the forward direction is still the same direction..

#

the graphics can be upside down, right way up, or spinning in circles.. the navmesh will still walk towards the Z axis

late bobcat
#

Hey there guys, i just joined this discord and wanted to ask a question about adding a score to my game in C#

rocky canyon
late bobcat
#

That's the code

deft siren
#

for the sake of it

rose galleon
#

hey, so, how do I keep a button pressed even when the player changes screens?

late bobcat
#

I wanted to make it with a flag. When object collides with player it augments score by one

edgy fox
#

I just modified my script for an orthographic camera view and now it is as if I have a really far away near clipping plane

#

what would cause this?

rocky canyon
#

ur near clipping plane..

#

sometimes its just a bug.. click an object and press F to focus on it.

#

but since thats in the gameview its probably just the clipping plane

rose galleon
rocky canyon
#

nope

edgy fox
rose galleon
#

ofc, adapt score and player to how you want to call them

rocky canyon
#

wont run.. ur function is wrong

rose galleon
ivory bobcat
rose galleon
late bobcat
rose galleon
polar acorn
ivory bobcat
#

If anything, you could update score in the Spawn function

late bobcat
edgy fox
#

and what gets clipped doesn't get affected by whether I zoom in or out

late bobcat
ivory bobcat
#
var next = Instantiate(...);
next.score = score;
next.collided = collided;```
polar acorn
polar acorn
#

You should decide which one object should "own" the score, and have the other objects tell that script to update its score

rose galleon
rocky canyon
#

this one guy used a -20

#

not sure i'd do that

edgy fox
#

ah negative clip planes

rocky canyon
#

but id def try moving the camera arounda bit

edgy fox
#

didn't know that was possilbe but makes sense

rocky canyon
#

lol ya, first time ive seen it too

polar acorn
#

If a negative clip plane fixes it then your camera is too close and you need to scooch it back

late bobcat
edgy fox
#

negative clip plane was not the solution,,, I did the Ultimate Doom oob glitch

clever thicket
#

Hey everyone, I'm trying to do different states wether my player is walking when jumping or idle, but can't seem to find a way to calculate the x and y velocity at the same time using else if, does anyone have any way to enlighten me on this?

ivory bobcat
rocky canyon
#

well dang, u decided to use -5000?!

edgy fox
#

and camera is 150 units away from objects that are clipping... moving it back didn't help

#

and in fact the farther away I move it the more clipping there is

warm depot
#

hello, how do I create a prefab asset with a script?

ivory bobcat
#

I was suggesting you update the next instances' values

late bobcat
#

Oh i see

rocky canyon
#

ur camera is just wigging out.. ur values are probably really odd lol

polar acorn
# clever thicket Hey everyone, I'm trying to do different states wether my player is walking when...

if takes in a single boolean. If you want to check multiple things in one you'll need to use some logical operators
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators

rocky canyon
#

just create a new camera and adjust it from a fresh start

polar acorn
edgy fox
#

its as if whenever I zoom out the screen doesn't grow

warm depot
#

ah I probably asked the wrong question but i found the instantiate thingy

polar acorn
eternal needle
edgy fox
#

(is that bad?)

polar acorn
#

Just wanted to make sure you weren't trying to zoom a 2D camera by moving it in or out

rocky canyon
#

🎉

edgy fox
#

what really gets me is that zooming in keeps the same area clipped

#

this is only really an issue when zoomed out

rocky canyon
#

search up google..

#

u got enough information to probably find some solutions

edgy fox
#

yeah I've googled a bunch but I'm pretty unknowledgable on cameras and my google searches haven't returned much

#

will keep trying though

rocky canyon
#

give me ur ground size and ur camera transform and ill see if i get the same issue

buoyant knot
#

is there an event function for when you save an SO? like OnValidate(), but for when you save it?

timber tide
#

what do you mean by save

#

serializing a value?

summer pulsar
#

i have a ball that follows box and should be destroyed when it touches the square

north kiln
sour fulcrum
#

Anyone know of a way to access objects in a newly additvely async loaded scene before the contents of the scene do oneanble/awake?

#

I was looking at AsyncOperation.allowSceneActivation but that doesn't give me access to the "preloaded" scene right