#💻┃code-beginner

1 messages · Page 418 of 1

slender nymph
summer pilot
#

hey im having a problem:

  1. my game loads
  2. i press play
  3. my game starts normal
  4. i press e to open my menu temporary keybind
  5. my game pauses and shows me the menu
  6. i press the menu button to go BACK to my menu
  7. i once again press the play button
  8. my game starts, but is paused
  • in order to unpause i need to press the e button again

im not sure what i need to provide to get help with this, please let me know

#

in the meantime I can provide a couple screenshots of the .cs files related to this

#

StartMenu.cs

#

PauseMenu.cs

slender nymph
#

sounds like you're setting the timescale to 0 when you open your pause menu, but aren't setting it back to 1 to close it

summer pilot
dry spruce
slender nymph
slender nymph
eternal falconBOT
summer pilot
#

downloaded and installed*

slender nymph
#

you've missed a step since you do not appear to have syntax highlighting for unity types

summer pilot
#

idk man it seems fine??

#

im looking at the thing you send and everything is adding up

slender nymph
#

regenerate project files and restart vs code.

summer pilot
#

C# and Unity are installed

summer pilot
slender nymph
#

and if you've never installed the .net sdk (such as through the c# dev kit extension) then you need to do that. and restart your computer

slender nymph
#

obviously yes, it's literally telling you what isn't installed and happens to be called exactly the same thing i said you need to have installed

summer pilot
slender nymph
#

i told you specifically you'd need the .net sdk. you now see vs code complaining that you need the .net sdk and giving you a link to download the .net sdk. please put some thought into this

winter tinsel
#

how can i hide the box collider in game mode?

#

nvm im stupid

slender nymph
#

depends on your definition of "hide" in this context

winter tinsel
#

i had the object selected thats why it showed its collider

slender nymph
#

ah, for the record gizmos are an editor-only thing. you wouldn't have seen that in a build regardless

summer pilot
slender nymph
#

did you restart your computer

summer pilot
#

ah, ill do that

dry spruce
summer pilot
#

restarted, still looks the same
not seeing any underlined issues

dry spruce
slender nymph
# summer pilot

it obviously does not look the same because now you've got syntax highlighting for unity types

slender nymph
# dry spruce

if a parent object has a rigidbody then this collider will be considered part of it, so you need to either mark the collider as Convex, make the rb kinematic, or disconnect this object from the rigidbody

summer pilot
#

the difference in these images (to me) is some color changes and the dimming of the top 2 lines since I did not use those systems in that script.

if i am missing something obvious please let me know

slender nymph
#

yes, the correct syntax highlighting is the difference.

summer pilot
#

alright then

slender nymph
#

nobody said that there would be any red underlines appearing in this code. it is just a requirement to have a configured IDE to get help with your code here
#854851968446365696

summer pilot
#

now that my IDE is setup do you need new screenshots of those two scripts?

slender nymph
#

no, you should share your !code correctly for help. but you also need to make sure you are actually calling that Resume method and not just disabling your menu or whatever

eternal falconBOT
summer pilot
#

PauseMenu.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    
    public GameObject pauseMenuCanvas;

    void Update()
    {
        //if (Input.GetKeyDown(KeyCode.Escape))
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (GameIsPaused)
            {
                Resume();
            }
            else
            {
                Pause();
            }
        }
    }

    public void Resume()
    {
        pauseMenuCanvas.SetActive(false);
        Time.timeScale = 1f;
        GameIsPaused = false;
        Cursor.visible = false;
    }
    void Pause()
    {
        pauseMenuCanvas.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;
        Cursor.visible = true;
        Cursor.lockState = CursorLockMode.Confined;
    }
    public void LoadStartScreen()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene("StartScreen");
        GameIsPaused = true;
    }
    public void QuitGame()
    {
        Debug.Log("Quitting game...");
        Application.Quit();
    }
}
#

StartMenu.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;

    public GameObject startMenuCanvas;

    void Start()
    {
        startMenuCanvas.SetActive(true);
    }

    public void LoadPlay()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene("Game");
        GameIsPaused = false;
    }
    
    public void QuitGame()
    {
        Debug.Log("Quitting game...");
        Application.Quit();
    }
}
summer pilot
slender nymph
#

now make sure it is actually being called

timber comet
slender nymph
#

i'll give you a hint as to what is happening: Resume is not being called by the button you close your menu with

summer pilot
#

but i dont see how that can be

#

because the timescale and cursor part of resume is working

#

also the toggling of the canvas works

#

waiiiit

#

line 19 does NOT get called, but line 34 DOES

#

so it is being called

slender nymph
#

that would mean that something else is calling that method

slender nymph
#

yes, like a button. not code, otherwise you'd see more than just 1 reference for the method

#

but if you confirmed that Resume is being called then you need to be more descriptive about what exactly is happening when you resume from the menu. or show a video

summer pilot
#

no other button is using PauseMenu.Resume

slender nymph
summer pilot
#

i dont have that many

slender nymph
#

well something is calling it if you get that log but not the other one. it may not necessarily be a button, that was just a suggestion

summer pilot
slender nymph
#

so the issue has been happening when you go back to the StartScreen scene from the pause menu? please make that clearer next time. you're using two separate GameIsPaused bools that have nothing at all to do with each other

#

why are you setting the game as paused when you go to the StartScreen scene anyway?

summer pilot
summer pilot
#

the only time its pausing is when the pause menu is opened

#

wait

slender nymph
#

you said i press the menu button to go BACK to my menu which did not make it clear you were changing scenes

summer pilot
#

wait no i didnt

#

i see why i did that

#

one sec

#

if i don't pause the game, my cursor is locked to the screen as if i am playing it. i don't have access so i can select an option

slender nymph
#

you know there's a simple line of code you can run to fix that, right? look very closely at how your Resume method works, then look at what you are doing differently in the LoadStartScreen method. also for the love of god stop showing off your code in video form

summer pilot
#
    public void LoadStartScreen()
    {
        Time.timeScale = 1f;
        GameIsPaused = false; //this is now false instead of true
        Cursor.visible = true;
        Cursor.lockState = CursorLockMode.Confined;
        SceneManager.LoadScene("StartScreen");
    }
#

is this what you're talking about with how it was different? this is what it looks like after i changed it

slender nymph
#

does it work now? also you could literally just call Resume from LoadStartScreen instead of copy/pasting all of that

summer pilot
#

no, it doesn't work now

#

the cursor doesnt even show still

slender nymph
#

you have saved the code, right?

summer pilot
#

yes i have

slender nymph
#

show the inspector for that menu button

slender nymph
#

ah wait, your resume hides the cursor. that's my bad, you'll need to make sure you're still manually releasing the cursor

summer pilot
#

that's not an issue here, i still didnt swap the resume over to the loadstartscreen

#
    public void LoadStartScreen()
    {
        Time.timeScale = 1f;
        GameIsPaused = false; //this is now false instead of true
        Cursor.visible = true;
        Cursor.lockState = CursorLockMode.Confined;
        SceneManager.LoadScene("StartScreen");
    }
#

this is still what is being loaded

slender nymph
#

then either you've got other code hiding the cursor or this method is not being executed. or it hasn't been saved.

summer pilot
#

this is the only other script i have

#

PlayerMovement.cs

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

[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
    public Camera playerCamera;
    public float walkSpeed = 7f;
    public float runSpeed = 12f;
    public float jumpPower = 7f;
    public float gravity = 17f;
    public float lookSpeed = 2f;
    public float lookXLimit = 90f;
    public float defaultHeight = 2f;
    public float crouchHeight = 1f;
    public float crouchSpeed = 3f;

    private Vector3 moveDirection = Vector3.zero;
    private float rotationX = 0;
    private CharacterController characterController;

    private bool canMove = true;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        if (!PauseMenu.GameIsPaused)
        {
            Cursor.visible = false;
            Vector3 forward = transform.TransformDirection(Vector3.forward);
            Vector3 right = transform.TransformDirection(Vector3.right);

            bool isRunning = Input.GetKey(KeyCode.LeftShift);
            float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
            float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
            float movementDirectionY = moveDirection.y;
            moveDirection = (forward * curSpeedX) + (right * curSpeedY);

            if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
            {
                moveDirection.y = jumpPower;
            }
            else
            {
                moveDirection.y = movementDirectionY;
            }

            if (!characterController.isGrounded)
            {
                moveDirection.y -= gravity * Time.deltaTime;
            }
            // Crouching
            if (Input.GetKey(KeyCode.LeftControl) && canMove)
            {
                characterController.height = crouchHeight;
                walkSpeed = crouchSpeed;
                runSpeed = crouchSpeed;

            }
            else
            {
                characterController.height = defaultHeight;
                walkSpeed = 6f;
                runSpeed = 12f;
            }

            characterController.Move(moveDirection * Time.deltaTime);

            if (canMove)
            {
                rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
                rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
                playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
                transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
            }
        }
    }
}
#

which hides the cursor when the game is not paused

languid spire
eternal falconBOT
summer pilot
slender nymph
#

no i didn't, i asked you to post your code correctly. which the bot shows you how to do

summer pilot
#

jesus my brain is fked

#

im so sorry

#

im gonna try something else

#

if i add another public bool named PlayingGame

#

i can set if the player is playing seperate to if the game is paused

#

so then in player movement i don't need to check if the game is paused, i just need to check if the player is moving

#

or is that stupid?

sharp abyss
#

How can I make my character walk like the games "daddy long legs" or "steppy pants" by pressing buttons and moving legs separately.I can lift the leg but cant make it go forward when I stop pressing button and should I use limits on hingejoints?

#

I added force when I getkeyup hope that works

winter tinsel
#

first if statement works, the debug tells me it reaches 50, but the second if statement never fires, even outside of the spawntime if

#

why??

#

its inside update()

slender nymph
#

you're checking if it is greater than 50. it can never be greater than 50 if you only increment it when it is less than 50

dapper sparrow
#

put >= in the second if statement i think

slender nymph
#

i do want to note that if this code is inside of Update then this will be faster with higher framerates

frank zodiac
#

is there an AND OR operator in c#?

teal viper
#

I want to see a programing language that doesn't 🤔

slender nymph
#

am i crazy or does AND OR just not make any sense? there's definitely the AND operator, and the OR operator, and XOR, but what the hell would an AND OR operator do? because if it requires both to be true, that's just the and operator, and if it only requires one of the two to be true, that's just the or operator

honest salmon
slender nymph
#

that's exclusive or. again, what the hell do you think AND OR is supposed to do?

slender nymph
frank zodiac
#

Also how do I generate a random integer? it only gives me float values as parameters

slender nymph
#

did you look at the docs

frank zodiac
slender nymph
#

well it's no wonder you didn't find anything helpful

honest salmon
frank zodiac
summer shard
#

How can i get the next value of a dictionary based on current key

slender nymph
#

dictionary keys are arbitrary, there is no "next" key. at best you can foreach over the dictionary but that doesn't sound like what you want

summer shard
# slender nymph dictionary keys are arbitrary, there is no "next" key. at best you can foreach o...

hmm, this is what i have rn and i want to get the next "objective"

public void completeObjective(Objective objective)
{
    if (currentObjective != objective) return;

    Objective nextObjective; // ???
    currentObjective = objective;
}

private void Start()
{
    foreach (Objective objective in GameObject.FindObjectsByType<Objective>(FindObjectsSortMode.None))
    {
        objectives.Add(objective.id, objective);
    }

    if (objectives.Count <= 0) return;
    objectives = objectives.OrderBy(obj => obj.Key).ToDictionary(obj => obj.Key, obj => obj.Value);
}
slender nymph
#

dictionaries are not ordered and the keys are arbitrary. "next" in your mind might not be "next" in the dictionary

#

use a list or array and just keep the current index then you can just ++ that index to get the "next" one

slender nymph
#

sure, why not?

summer shard
#

i thought you can't sort lists??

slender nymph
#

why would you think that? there's literally a List.Sort method

summer shard
#

OHHH, i didn't see that, thanks

broken cargo
vast vessel
#

is this a good way to calculate falloff with a min and max distance? (im going to use this for my AI hearing sensors)

summer shard
broken cargo
summer shard
broken cargo
summer shard
#

okayy, thanks

silk night
vast vessel
#

evaluating a curve would probably have a higher impact on the performance so i dont think its worth it

queen adder
#

I couldn't find an answer anywhere online but, Is it possible to use LUA in unity? Trying to transfer softwares but I only breifly understand other programming languages.

slender nymph
#

there are probably assets/packages that allow you to include lua scripting for within your game. but unity's scripting language is c# so you will need to learn c# if you want to make a game in unity

queen adder
slender nymph
#

there are beginner c# courses pinned in this channel to help you get started

wintry quarry
#

but no you're not going to be able to just dump Roblox code into Unity.

naive locust
#

damn

slender nymph
naive locust
#

is there any issue with detecting inputs like this?
when i use just "Input" it comes up with an error

slender nymph
#

you probably have your own class called Input

wintry quarry
#

Just saying "an error" isn't very specific

naive locust
#

oh mb lemme run it

fierce geode
#

Hey, Don't know if this is an important enough question.
But where should the responsibility lie in two objects when they interact to who executes the code. Like on a simple level, when an enemy damages the player; to which should the deal damage code be placed. Should the code for dealing damage be placed in the enemy's script or should the player script have the code for taking damage?

Does it matter? Is there some kind of design methodology to follow or is it just semantics?

naive locust
wintry quarry
# naive locust

get rid of using UnityEngine.Windows; at the top of your script

slender nymph
naive locust
#

ohhh ok

#

ty

frosty hound
slender nymph
# fierce geode Hey, Don't know if this is an important enough question. But where should the r...

separate dealing damage from taking damage. the responsibility of dealing the damage should be on whatever is actually causing the damage. then whatever is receiving the damage can have some specific component (or an interface) for receiving that damage. that way neither object needs to specifically know about the other, the damage dealer just looks for that damage taker component and applies the damage

queen adder
fierce geode
#

Thanks 👍

wintry quarry
#

there's no replacement for that

fierce geode
eager spindle
#

in 2024 😨

atomic holly
#

Hello !
I want to use an extern collider of my script and verify if this collider is touching and other collider wiht the tag "Enemy". Can I use a OnCollisionEnter2D or not ?

slender nymph
#

OnCollisionEnter2D would only be called on the object that has the collider or its rigidbody parent (if it has one). if your component is not attached to that same object then it will not receive the OnCollisionEnter2D message for that collider

#

if you explain your actual use case, a better solution can be suggested

atomic holly
#

I don't want to use a collider of the object himself but a collider of his children

wintry quarry
atomic holly
slender nymph
#

if the component is on the same object as the Rigidbody2D then it will receive the OnCollision message

wintry quarry
atomic holly
slender nymph
#

well you've still not bothered saying what any of this is for so 🤷‍♂️

wintry quarry
#

Note that Collision2D tells you which colliders were involved

#

So you can always check in your code if it's the appropriate collider

atomic holly
#

But the script PlayerDamage is in the Player gameObject

#

So, I integrate the collider of the weapon in the script like this

slender nymph
#

well like Praetor pointed out, the Collision2D parameter of the OnCollisionEnter2D method will provide information about the colliders involved in the collision.
although i personally would either disconnect the weapon from the player entirely and give it its own component or use physics queries

atomic holly
slender nymph
#

is there a specific need for it to be a child? if the only need for being a child is following the player, there are plenty of options for doing so without being a child

wintry quarry
#

For detecting attacks, physics queries are usually the way to go

#

unless this is some kind of active ragoll QWOP style game

atomic holly
atomic holly
slender nymph
atomic holly
#

I'm not very fluent in English it's maybe why you think i'm little agressive

#

But I just want to know your process of why you should take the weapon out of the player

slender nymph
#

i told you why . . .

#

if there is no specific need for it to be a child of the player then i wouldn't make it a child of the player. that's literally it

atomic holly
#

Okay, thanks a lot guys

balmy grove
#

hello

winter tinsel
#

as a prefab it wont let me drag the player into the "target"

#

what do i do

#

im guessing tags?

wintry quarry
#

FindWithTag is one option, sure

#

Or just having the spawner give the new instance the reference directly

winter tinsel
#

how do i use findwithtag

wintry quarry
winter tinsel
#

found it

#

thanks

atomic holly
#

I write this and when I do a left click, the hello is send directly and not 10 seconds after. Did I do something wrong ?

private void Update()
{
    //Vérifie si le clic gauche est pressé
    if (Input.GetMouseButtonDown(0))
    {
        weaponCollider.enabled = true;
        StartCoroutine(WaitSeconds(2));
        weaponCollider.enabled = false;
        Debug.Log("Hello");
    }
}

private IEnumerator WaitSeconds(float seconds)
{
    yield return new WaitForSeconds(seconds);
}
wintry quarry
#

they only delay themselves

#

your coroutine here effectively does nothing

#

You would need to put the log INSIDE the coroutine for it to be delayed:

private IEnumerator WaitSeconds(float seconds)
{
    yield return new WaitForSeconds(seconds);
    Debug.Log("Done waiting");
}```
atomic holly
#

Oh okay, I see

#

Thanks 👍

hearty anvil
#

Hello everyone, I'm trying to make obstacles move faster as the score increases. After scoring 14/24/34/44/54... points, a larger gap appears between only one set of two obstacles. It wasn't doing this before I added the function to speed up the game.

wintry quarry
hearty anvil
cosmic quail
summer stump
#

Ah, missed the part where you said only one set of the two obstacles.
My answer is likely wrong then

icy grotto
#

hi, is there something like this that would check for UI layer?

#

EventSystem.current.IsPointerOverGameObject

wintry quarry
azure hemlock
#

why is the picture (heightmap) (dark as u can see) imported as white in unity? how do i turn off this shit?

silk night
#

can you show the result in unity?

azure hemlock
#

its on the right

#

even when i encode it to a file using c# it gets encoded as the white one unity made.

silk night
#

can you send the heightmap file here? ill try on my own unity

wintry quarry
#

The better approach is to switch to using the event system for your click interactions @icy grotto

azure hemlock
#

here is it

silk night
#

uhh look at the height map in browser like chrome, its white there too

#

wtf

azure hemlock
#

lol

#

wtf

#

makes no sense

icy grotto
#

anyway thank you!

silk night
naive locust
#

what does void mean and what is it used for?

silk night
polar acorn
naive locust
#

so what would you do if you want a return?

cosmic quail
polar acorn
cosmic quail
#

and then at the end you gotta type "return <thing>;"

azure hemlock
naive locust
#

oh so for example

string WriteASentence(sentence)
{
  ...
  return sentence;
}

?

polar acorn
frosty hound
#

(Which does not have to be at the end, as incorrectly stated above)

#

You can return out of the function whenever you want. If it's a void return, then you can just return. Otherwise, you have to return something of that type: return "MySentence";

polar acorn
#

Right, it can be used to exit the function early, which can be used for example when you're looking for a specific element in a list. You can return the value before the loop finishes to prevent wasting time checking after it's found

cosmic quail
frosty hound
#

Yes, which is correct when stated correctly like that.

naive locust
naive locust
#

ok

#

thx

quick ruin
#

is there a reference to the top face of the box collider?

wintry quarry
winter tinsel
#

nullrefrenceexception

#

is it because im deleting it then calling more code from it?

summer stump
#

Where do you assign shippy?shipping? And is it a child of the gameObject?

rocky canyon
#

u know gameObject is the script the collisionenter is on.. and not the other one right?

#

ur destroying that script instead of the other object

wintry quarry
winter tinsel
#

how is shippy a null refrence tho

wintry quarry
winter tinsel
#

shippy is a script

wintry quarry
#

or you assigned it to null

rocky canyon
#

idk.. why u not assigned it?

winter tinsel
#

im calling a script

wintry quarry
summer stump
winter tinsel
#

public shipscript shippy

wintry quarry
#

which are null by default until you assign them.

summer stump
wintry quarry
#

until you assign them.

winter tinsel
wintry quarry
summer stump
#

= sign
Or in the inspector

winter tinsel
#

what

wintry quarry
#

that's the assignment operator

#

or, you assign in the inspector

summer stump
#

shippy = [something]

Or drag and drop the object with the script via the inspector

wintry quarry
summer stump
winter tinsel
summer stump
wintry quarry
winter tinsel
winter tinsel
#

allright

#

thanks

rough orbit
#

I know I've missed something fundamental here, but the error message "'Collision2D' does not contain a definition for 'tag' and no accessible extension method 'tag' accepting a first argument of type 'Collision2D' could be found (are you missing a using directive or an assembly reference?)" tells me nothing.

It works fine for OnTriggerEnter2D. What am I not getting?

wintry quarry
raw token
rocky canyon
#

collision.gameObject

wintry quarry
cosmic quail
rocky canyon
#

why u have Trigger and Collision?

cosmic quail
#

why does ur code make it look like OnTriggerEnter is inside Start 😄

rough orbit
wintry quarry
#

OnCollisionEnter2D only accepts a Collision2D parameter

rough orbit
wintry quarry
#

If you don't use Collision2D as the parameter it's not going to get run by Unity at all

rough orbit
burnt vapor
#

Consider looking up the documentation of these collission methods

rocky canyon
rocky canyon
hallow acorn
#

does somebody know what quaterion.w is?

rocky canyon
#

its the magic 4th dimension

hallow acorn
#

ok so what should i do if it says i have to put a 4th float??

rocky canyon
polar acorn
polar acorn
rocky canyon
hallow acorn
#

Instantiate(projectilePrefab, transform.position, new Quaternion(transform.rotation.x, Random.Range(FirePoint.transform.rotation.y - 3, FirePoint.transform.rotation.y +3), FirePoint.transform.rotation.z));

#

what should i do instead?

polar acorn
rocky canyon
hallow acorn
#

(and is there a way to make this shorter i just want to set the y rotation)

polar acorn
rocky canyon
#

don't mess w/ quaternions directly..

#

unless ur a math major

hallow acorn
#

yeah im definitly not haha

#

but siriously wtf does the 4th dimension mean in that context???

rocky canyon
#

dont worry about it

rough orbit
#

Gonna have to read up on why

rocky canyon
hallow acorn
hallow acorn
polar acorn
rocky canyon
#

lmao

polar acorn
#

They're not related to the three spatial dimensions

#

They're not "X axis, Y axis, Z axis, and some fourth thing" none of the values have anything to do with any of the axes of 3D space

hallow acorn
polar acorn
#

The 3D space comes from the interaction between those values

polar acorn
#

Never make quaternions by hand

rocky canyon
#

like i said, its best to ignore them.. and just know they're magic

hallow acorn
#

bro i dont even understand normal wikipedia articles xD

rocky canyon
#

use helper functions to convert Eulers.. (what we're familiar with) to quaternions

hallow acorn
#

ok how does the index of the set eulerAngle work im stupid i guess

rocky canyon
#

index?

hallow acorn
rocky canyon
#
        // A rotation 30 degrees around the y-axis
        Vector3 rotationVector = new Vector3(0, 30, 0);
        Quaternion rotation = Quaternion.Euler(rotationVector);```
#

Quaternion.Euler (regular vector 3)

hallow acorn
rocky canyon
#

no worries 👍 just here to help when i can

winter tinsel
#

ok one last thing before the very prealphademowhateveryouwannacall it of my starter game is finished

#

how do i make a radius in which enemies spawn randomly?

#

random.insideunitcircle works but it spawns things inside the playarea

#

when i need them to spawn outside

#

can i just make the playarea somehow a place where they cant spawn? like form 9 to -9 and 5 to -5 and everywhere in between you cant spawn it so pick a different place

broken cargo
winter tinsel
#

doesnt really matter what shape it is

#

just that the enemies spawn outside of a determined area

broken cargo
winter tinsel
#

how do i set those

#

Vector2 minbound = ??
Vector2 maxbound = ??

#

and then how do i make it spawn between those bounds

broken cargo
# winter tinsel how do i set those

You can use Random.insideUnitCircle for direction and than randomize a float between min and max to get a point that is atleast min from the center

winter tinsel
#

direction??

broken cargo
winter tinsel
rocky canyon
#

makes it a 0 or 1 value

broken cargo
polar acorn
rocky canyon
#

yea ^

polar acorn
#

not 0-1

rocky canyon
#

lol.. bad punctuation

#

u normalize ur direction.. and then multiply it by ur distance..

#

ensures consistency

winter tinsel
broken cargo
rocky canyon
#

even unity docs has weird punctuation

#

1.0. eh? lol

short hazel
#

1 [decimal point] 0

broken cargo
winter tinsel
#

ok so can i do something along the lines of

rocky canyon
winter tinsel
#

wait then how does it amount to a vector?

#

if its a float?

short hazel
#

It's the length of the vector

winter tinsel
#

on what axis

#

x or y

#

or whichever one we want?

rocky canyon
#

1 and 1.0f are practically the same distance.. they said f to clarify it was 1.0

polar acorn
summer stump
polar acorn
#

It makes the magnitude of the vector 1, unless that magnitude is 0

#

in which case it remains 0

broken cargo
short hazel
#

When you normalize a vector, it will scale the XYZ so the resulting magnitude is 1

broken cargo
#

Vector2.one.normilized points north-east but it's magnitude is 1.0f instead of 1.41f

rocky canyon
#

when u get the random points he's saying make it a direction..

#

normalizing just keeps em all ranged at 1

#

u still get a direction.. but it keeps it uniform when u go to multiply it by distance

#

so (1) direction * 10 is the same distance from u as (2) direction * 10

short hazel
#

Forgetting to normalize is a very common cause of the "why am I faster when going diagonally?" problem

rocky canyon
#

first problem i ever solved 🙂

hallow acorn
#

what exactly is the difference between referencing a component by hand using public and using getcomponent?

polar acorn
#

GetComponent is used for the times you can't

hallow acorn
#

oh im using it by myself ig

#

but i just followed the tutorial

hallow acorn
polar acorn
#

If you are trying to reference a component from an object you get at runtime through various means

#

such as if it's spawned in, or you want a component from something like a raycast or OnCollision

hallow acorn
#

ok ty

late burrow
#

so primitives cant be null but entries inside array can

willow scroll
languid spire
late burrow
#

i legit have string array where some entries are null

willow scroll
#

It's a class and a reference type

languid spire
#

string is not a primitive

willow scroll
#
public sealed class String { }

public readonly struct Int32 { }

public readonly struct Boolean { }
summer stump
late burrow
#

but if a string is reference would it mean copying its contents to another variable makes them both shared?

slender nymph
#

yes, but strings are also immutable so every time you modify a string it creates a new string object

#

considering how you are trying to make c# a stringly typed language, you should really consider learning how strings actually work

slender nymph
rich adder
#
 public struct Nullable<T> where T : struct
 {
     public Nullable(T value);

     public bool HasValue { get; }
     public T Value { get; }

     public override bool Equals(object other);
     public override int GetHashCode();
     public T GetValueOrDefault();
     public T GetValueOrDefault(T defaultValue);
     public override string ToString();

     public static implicit operator T?(T value);
     public static explicit operator T(T? value);
 }``` oh shiee
#

and also value gets null as yea

eternal needle
rich adder
#

yeah feels a bit awkward

summer stump
#

Every time I begin implementing nullables, I end up tearing then out

rich adder
#

I wonder what the though was there for adding it. I've only had it a few bools before, forgot why I even had it though lol

broken cargo
languid spire
eternal needle
#

It's definitely a niche case to need one though, at least in unity imo

languid spire
#

not so sure, imagine Vector3? target. Allows you to know if a target exists without the usage of an extra bool

rich adder
queen adder
#

I need some help Im trying to give this gameobject a TMP and it just wont format properly

broken cargo
short hazel
#

Also UI elements are not anchored, they won't move if you change the resolution

queen adder
#

I moved the canvas into the base it seems to be working thank you and @rich adder navarone i wont do it again I had no idea lol

queen adder
#

yep thank you and another question ive got a SO and im wondering how I can turn a float into the SO's value

rich adder
queen adder
#

I got a float "currentHealth" I want it to equal the SO value

rich adder
#

SO is a class

#

classes contain floats or whatever type , how would assigning float to a class make sense

queen adder
#

Im now confused

#

The SO is being accessed from another script

rich adder
queen adder
#

Because I got a health bar I want the heathbar to equal the SO value so I want current health(Current heath is what makes the heathbar value) to equal the SO

tawdry rock
#

Can someone help me with scriptable objects? I made a base scriptable object class name ItemSO, then i made another one called FoodSO. this inherits from ItemSO then i made a Monobehaviour script called Items that holds a refference for ItemSO public ItemSO item; and i dragged the file to the refference slot thats is made with FoodSO. Now this Items class sit in a gameObject and i have a button has a method that requires a gameObject. UseBTN(GameObject itemToConsume); I get and pass the gameobject refference via mouse hoover and now if i try to set a UI element with descriptionText.SetText($"You restored {itemToConsume.GetComponent<Items>().item.hunger} amount of hunger."); this gets me a error and says ItemSO doesnt contain "hunger" (because FoodSO contains it.) Why can't i access it?

rich adder
#

two SO questions back to back notlikethis

languid spire
eternal needle
queen adder
queen adder
rich adder
young fossil
#

Hello. I have a question: is it a fair assessment to say the games dev community have much less error handling than in other software dev?

queen adder
#

I dont know what that is will that explain it also why arent yo usuposed to change the values on SOs?

young fossil
#

You mean most community have no error handling at all

rich adder
languid spire
queen adder
young fossil
tawdry rock
rich adder
languid spire
queen adder
rich adder
#

if player crashes or leaves game they lose all their coins

young fossil
queen adder
#

How should I be storing the values?

languid spire
young fossil
#

Since you are experienced in the industry, if you were looking through code with no error handling vs code filled with error handling, which coder would you prefer to work with off the bat?

#

Even simple null checks

#

and error logs for unexpected behaviour

rich adder
queen adder
languid spire
young fossil
rich adder
young fossil
#

Or is it a practise that has been pushed on to people without much use

languid spire
queen adder
polar acorn
languid spire
young fossil
rich adder
tawdry rock
# polar acorn What is `item`

item is the name given to hold refference for the scriptable object public ItemSO item; and FoodSO inherit from ItemSO

eternal needle
polar acorn
languid spire
queen adder
rich adder
young fossil
#

Also why do I never see
throw new InvalidOperationException
and error handling syntax like this often in Unity dev?

queen adder
rich adder
languid spire
tawdry rock
polar acorn
young fossil
queen adder
polar acorn
languid spire
tawdry rock
young fossil
languid spire
polar acorn
eternal falconBOT
young fossil
languid spire
queen adder
#

Are the unity docs the place to learn everything (like playerprefs)

young fossil
#

So for solo devs, who don't have the luxury of full QA teams and dedicated play testing groups, it is viable to go the app level route, but use complier code and a combination of self playtesting?

languid spire
languid spire
slender nymph
#

i'm pretty sure the issue is because your cast and parentheses are fucked up. shouldn't it be (FoodSO)(itemToConsume.GetComponent<Items>().item).hunger

#

or maybe one extra set of parentheses

languid spire
tawdry rock
languid spire
#

the point is, casing item to FoodSO so the hunger property can be accessed

slender nymph
#

lol what ever happened to "I compile every line of code i write into IL in my head"

languid spire
polar acorn
tawdry rock
polar acorn
tawdry rock
#

Yes, i know it's dumb because i could determine with the enums category but for the shake of practice i made it.

queen adder
#

Would playerpreffs go in start or update or their own thing

polar acorn
summer stump
#

Loading, then sure awake or start is good

twin harness
#

im facing a weird issue with the input system.

using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;

...

    private void Awake()
    {
        EnhancedTouchSupport.Enable();
    }
    void Update()
    {
        if (Touch.activeFingers.Count == 1)
        {
            Touch touch = Touch.activeFingers[0].currentTouch;
            Debug.Log("Touch phase: " + touch.phase);
        }
     }

But when I press once and hold, it keeps showing the phase Began again and again.

#

Any idea what might be the issue here?

viral hatch
#

Idk where to put this so this is probably wrong but

Im trying to make a VR Hand setup, but "XR Controller (Action-Based)" Is not appearing, How can I fix this or make a working hand?

queen adder
olive galleon
#

should i subscribe to events in awake or start

summer stump
#

Is the event in the same class? Or a different one?

polar acorn
tawdry rock
summer stump
#

Random.Range gives a float value. Plug those values into a Vector

queen adder
#

Vector2 name = new Vector2(Random.Range(number, number), Random.Range(number, number));

#

np

#

I got a question what the heck is wrong

#

{
public TMP_Text coinText;
public int Coins = 0;
// Start is called before the first frame update
void Start()
{

}


// Update is called once per frame
void Update()
{
    coinText.text = PlayerPrefs.GetInt("Coins", Coins);
}
public void SaveData()
{
    PlayerPrefs.SetInt("Coins", Coins);
    PlayerPrefs.GetInt("Coins", Coins);




}

}

#

This is what is not working void Update()
{
coinText.text = PlayerPrefs.GetInt("Coins", Coins);
}

#

says I cant turn int into string

rich mountain
#

turn the int into a string

queen adder
summer stump
#

Also load the data once. Not in update

wanton pecan
#

Guys what mobile apps do y'all suggest for Beginners

queen adder
wanton pecan
#

Or short vids

#

Teaching

#

That r actually fun

#

Not boring

polar acorn
#

for what

summer stump
#
void AddCoins(int amount) {
  Coins += amount;
  coinText.text = Coins;
}
#

There is no reason at all to do any of that in update

warm raptor
#

hello here is the part of the script of my serveur that send the infos of all the player of the game to each player of the game, but when someone disconect this part of the the script tell me that message can't be send to the player that has disconected. How can I make to remove the player from the dictionnary if the serveur can't send message to this player ?

public void SendToGamePlayers(string gameId, string message)
{
    if (GameDict.TryGetValue(gameId, out var game))
    {
        foreach (var playerId in game.Players.Keys)
        {
            Sessions.SendTo(message, playerId);
        }
    }
    else
    {
        Console.WriteLine($"Game with ID {gameId} not found.");
    }
}
bold plover
#

Man. Bit the bullet with learning a state machine I felt was jank but decent to start with but now I think I'd have to use a lot of double code to implement it in a manner appropriate for my purposes. Sheesh.

#

Lessons learned.

#

Like I'd have to pass the proper stats from one state to the current state script and the current state script back to what I'm using to control movement. damn

#

lmao

#

Feels like in the end that defeats the point of the state machine.

wanton pecan
raw token
hallow acorn
#

why does it say that? "UnityException: Invoke repeat rate has to be larger than 0.00001F)"
InvokeRepeating("LaunchPrefab",1 , Random.Range(spawnRate - 2, spawnRate + 2));

cosmic dagger
hallow acorn
warm raptor
# raw token If it's actually throwing an exception, you can use [try/catch blocks](<https://...

I already tried to do that, but It seam that it didn't work

public void SendToGamePlayers(string gameId, string message)
{
    if (GameDict.TryGetValue(gameId, out var game))
    {
        foreach (var playerId in game.Players.Keys)
        {
            try
            {
                Sessions.SendTo(message, playerId);
            }
            catch (Exception ex)
            {
                game.Players.Remove(playerId);
            }
        }
    }
    else
    {
        Console.WriteLine($"Game with ID {gameId} not found.");
    }
}
eternal needle
hallow acorn
polar acorn
cosmic dagger
eternal needle
hallow acorn
cosmic dagger
# wanton pecan Learning code

It's easier to read a website, watch video tutorial, or even do a course. Most coding apps teach the bare basics (minimum) of a language and leave the rest behind pay walls. There's no telling how in-depth they go into the language as well . . .

raw token
eternal needle
warm raptor
eternal needle
queen adder
#

Hi everyone. I'm not understanding coroutines. If I put a coroutine in the Update, it just repeats infinitely without waiting. How can I make this code work? This coroutine gets executed only once.

ivory bobcat
eternal needle
queen adder
hallow acorn
polar acorn
ivory bobcat
polar acorn
#

You might want to either put it in a loop, or call StartCoroutine after the wait

eternal needle
queen adder
queen adder
eternal needle
queen adder
#

So coroutines are just normal functions (?). Why do we call the "coroutines" if I can make my own function and repeat getting the same result? Does a coroutine has something more?

eternal needle
#

Actually, turn off collapse in your console and itll be more clear

polar acorn
#

So we can see them all in order

eternal needle
#

Damn digi too fast

queen adder
hallow acorn
queen adder
#

void Start()
{
LoadData();
instance = this;
coinText.text = "Coins: " + Coins.ToString();
Coins = PlayerPrefs.GetInt("amountCoins");
}

// Update is called once per frame
void Update()
{
    if(Input.GetKeyUp(KeyCode.Escape)) 
    {
        AddCoins(1);
    }
    
}
public void SaveData()
{
    PlayerPrefs.SetInt("amoutCoins", Coins);
    
}

public void LoadData() 
{
    PlayerPrefs.GetInt("amountCoins"); 
}

    public void AddCoins(int amount)
{
    Coins += amount;
    coinText.text = "Coins: " + Coins.ToString();
}

}

I am confused this should be setting the playerPref to coins on start but when I play add coins then stop game then reboot it it resets the coins anybody know what ive done wrong?

polar acorn
eternal falconBOT
queen adder
polar acorn
queen adder
#

!code void Start()
{
LoadData();
instance = this;
coinText.text = "Coins: " + Coins.ToString();
Coins = PlayerPrefs.GetInt("amountCoins");
}

// Update is called once per frame
void Update()
{
    if(Input.GetKeyUp(KeyCode.Escape)) 
    {
        AddCoins(1);
    }
    
}
public void SaveData()
{
    PlayerPrefs.SetInt("amoutCoins", Coins);
    
}

public void LoadData() 
{
    PlayerPrefs.GetInt("amountCoins"); 
}

    public void AddCoins(int amount)
{
    Coins += amount;
    coinText.text = "Coins: " + Coins.ToString();
}

}

eternal falconBOT
ivory bobcat
polar acorn
hallow acorn
summer stump
polar acorn
queen adder
hallow acorn
#

thanks a lot you helped me out once again

summer stump
queen adder
#

public void LoadData()
{
PlayerPrefs.GetInt("amountCoins");
Coins = PlayerPrefs.GetInt("amountCoins");
}

#

I think I need to save it somewhere

#

Im very confused

#

!code

eternal falconBOT
summer stump
#

And that is loading, not saving, so I am not sure what you mean.

#

Ah, you mean to the variable

#

If there is an amountCoins in playerPrefs, that is how you would do it

sharp abyss
#

I am trying to walk my character manually but I did it by adding force when getting key up(when I stop holding button , it gets leg to normal rotation).I dont think thats the proper way to do that.If you couldnt understand, games "daddy long legs" and "steppy pants" are some examples.

queen adder
#

Im not sure whats wrong I click esc to save it dbug says I am then i do it again but it isnt

summer stump
queen adder
sharp abyss
wintry quarry
#

I would say - more like setting joint properties than adding forces manually.

sharp abyss
summer stump
queen adder
#

Ok

queen adder
#

ill run it and see

#

That did not work

summer stump
summer stump
queen adder
summer stump
#

Look closely at the spelling

#

You made a spelling error

queen adder
#

holy moly...

#

It fixed well thats 30 mineuts wasted

#

hey at least I understand playerprefs now sweet

tall nest
#

Hello everyone, how's all going? I hope you're good
Please help me fixing these errors, I got 26 error

short hazel
polar acorn
tall nest
polar acorn
#

Possible, if it was full when you tried to install it

#

things couldd be missing

tall nest
#

because when I launch the project it keep saying not enough space

fickle plume
#

@tall nest Remove hate speech from your pronouns or you will be removed from the server.

tall nest
#

My main disk keep refilling

#

why?

#

I can't free anything anymore

polar acorn
tall nest
#

I always delete and it fills again

polar acorn
tall nest
#

it's some windows stuff

polar acorn
#

So then there's probably other things that are trying to go into your drive but can't because it's too full which means you're gonna probably need to aggressively clean up some space

tall nest
#

Can I just move my user into the other disk so the packages get installed in the temp folder or smth?

polar acorn
#

Moving files to another place on the hard drive does not make the hard drive less full

tall nest
lusty plover
#

I am trying to use the Unity AI But i got these errors after installing the library. Any help?

tall nest
#

Will it cause confuse to the Apps or no

polar acorn
# tall nest Will it cause confuse to the Apps or no

I can't answer that without knowing everything installed on your machine and how you're configured. If there's literally nothing you can think of that can be deleted or moved your hard drive is probably just not big enough

fickle plume
tall nest
polar acorn
tall nest
#

Then why does it say not enough space, I have placed my project in the disk that has around 70GB free

fickle plume
#

@tall nest Also has no relation to the code channel.

tall nest
#

"Fogsight"?

#

:/

fickle plume
polar acorn
tall nest
glad ore
#

after every X minutes i want to display an ad for android game . what is good value for X ? which balances frustation of user and my revenue .

calm forge
#

can someone help i am new to unity and c#, i was following a yt vid and making angry birds when i was faced with this problem pls help 🥲

calm forge
#

idk

#

i followed the vid idk if i can share the link

fickle plume
#

@calm forge You need to finish installing !ide

eternal falconBOT
polar acorn
#

Sure, send the link

#

and then do what fogsight just linked

calm forge
fickle plume
polar acorn
# calm forge https://www.youtube.com/watch?v=QplEeEAJxck&t=284s
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 169
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-07-09
modest dust
#

Looks like there's a need for a tutorial on how to follow a tutorial

calm forge
polar acorn
calm forge
#

lemme check

calm forge
#

i just deleted where thier was red line i dont think i did mistake in spelling but oh well i works now

polar acorn
ivory bobcat
polar acorn
#

and compare that word to the tutorial's

ivory bobcat
#

Human error is common and should be considered the first to be questioned when debugging code from tutorials - which thankfully an ide that's configured might be able to assist with (green squiggly line)

calm forge
queen adder
#

Is there a way to make a int from another script work for the one im on?

sharp abyss
#

I dont kow if its the proper way but first you can get the script by public *yourscriptsname *yourscriptname and I think you can access it like that

#

then you can create an int in the script you write this and equalize it to the other int if you need

queen adder
#

thank you lots

ivory bobcat
# queen adder Is there a way to make a int from another script work for the one im on?

Assuming you've got an instance of that script (an object in the scene that has that script component attached) you'd reference that object as the component type (drag it into a field with that script component as the type) and be able to access that specific instance's integer membercs public MyScript myScript;//field that should have been assigned from the inspector private Start() { myScript.myInteger = 5; }

radiant frigate
#

even if i have the collisions matrix somehow the collision keeps happening

#

does someone know if this is a recurrent thing or am i just dumb?

silk night
radiant frigate
#

oh i discovered why, saw someone having the same problem, we basically used the wrong physics

#

yes

#

i was using physics when i should be using physics2D

#

my bad srry

#

ty tho!

open vine
#

Hey does anyone know how I would make an object change to the next color when I interact? I have an array of materials and a reference to the objects mesh renderer. I want to change it to the next material in the array everytime I interact. I know I have to meshRenderer.material = materials[0] to set it, but how do I make it iterate to the next one each time?

sand heath
#

if you want to change the material to a different one, just increment the index

#

materials[0], materials[1], materials[2] etc

open vine
sand heath
eternal falconBOT
sand heath
#

i need to know what you're doing before i can say what you should do

#

@open vine the way you have it looks perfect to me? does it not work?

#

ohh i see

open vine
#

Yeah it actually skips right to the last one

sand heath
#

well yeah cuz you have the for loop going through every material when interact with it

#

so instead, make an integer to store the index and then increment that index everytime you interact with it

#

then set the material to material[index]

#
private int materialIndex;

public void Interact()
{
  materialIndex++;
  screenRenderer.material = CCTV_Materials[materialIndex];
  if (materialIndex == CCTV_Materials.Length)
  {
    materialIndex = 0;
  }
}
#

oh oops forgot to increment

#

u get the point tho

open vine
#

Oooh thats really smart it works perfectly fine now thanks for explaining why I do this as well!

sand heath
#

though this way should work completely fine without touching any of that

open vine
#

gotcha, tbh I have no clue how shader graph works but if I ever need the color swapping ill look into it 👍

open vine
#

oh wow, is it really useful? I have 0 art skills and I kinda just viewed shader graph as an artist exclusive tool

sand heath
#

super powerful and kinda fun

queen adder
#

Are Rigidbody player controllers always messy looking? Mine works fine but I wanna organize it, but I cant really do it

sand heath
#

gives you better control (being able to code your own gravity, velocity, etc)

queen adder
#

CC is good for horror games and that sort of stuff

sand heath
#

you sacrifice control for a physics-based solution that is easy to implement

queen adder
#

Yeah, number 2 is quite good for almost all cases though

#

But some physics games must have 1

sand heath
#

imo 1, 3, and 2 in order of difficulty - 1, 2, 3 for level of control

#

and i guess the 4th secret option of creating all your own collision and physics

queen adder
sand heath
#

difficulty of implementing/writing the code for yeah, control meaning how customizable/flexible it is

#

(you can override/inherit from the charactercontroller to customize it further)

queen adder
#

Yeah, I would always use 2 if it wasn't for the fact that external physics forces barely affect it, since the velocity is set directly in the code

sand heath
#

you can also look at the asset 'kinematic character controller'

queen adder
#

But im not good at player controllers whatsoever so not for me

#

Since you gotta write your own stuff it says

sand heath
#

it does have a pretty good walkthrough included in the files, it's pretty advanced though

#

it allows for a good amount of control for that cost

queen adder
#

Pretty much just better CC

sand heath
#

its more like a better rigidbody

#

its a lot more difficult to use than CC i think

frosty hound
#

It's a kinematic character controller, it's nothing like a rigidbody that uses physics.

#

It's closer to the built in CC, with more utility functionality

digital cave
#

How do I access Volume and it's settings, enable/ disable specific post processing effects in code? I can not find anything about it in unity scripting documents.

digital cave
# summer stump Is this the URP?

Yup, just found the solution (I have been trying for the last 20 minutes, and I found the it moment I asked in here)

        Volume volume = FindFirstObjectByType<Volume>();
        
        DepthOfField depthOfField;
        ColorAdjustments colorAdjustments;

        if (volume.profile.TryGet<DepthOfField>(out depthOfField) && volume.profile.TryGet<ColorAdjustments>(out colorAdjustments))
        {
            depthOfField.active = false;
            colorAdjustments.active = false;
        }
topaz mortar
#
[SerializeField] private int test;```
Why is healthBar not showing up in my inspector?
I just added the test and that does show up
#

Nvm, was using using UnityEngine.UIElements; instead of UnityEngine.UI;

glossy turtle
#

how to check if all gameobjects has the same value.
the gameojects has a script and the script has int value.
how to check if int value is same for all gameobjects.

silver pier
#

does anyone know how i can code a login? thnak you.

eternal needle
glossy turtle
#

i am trying to check if the int value is same for all gameobjects so that i can show end screen;

eternal needle
hallow acorn
#

i think u can see in the video but spawnRate is set to 15

eternal falconBOT
glossy turtle
#

there is an array of gameobjects and i am checking if all int values are same like say 1 for all gameobjects.

hallow acorn
# eternal needle show the full !code

public class CanonMain : MonoBehaviour
{
    public GameObject projectilePrefab;
    public GameObject FirePoint;
    public float spawnRate;

    void Update()
    {
        InvokeRepeating("LaunchPrefab",10 , Random.Range(spawnRate - 2, spawnRate + 2));
    }

    void LaunchPrefab()
    {
        Instantiate(projectilePrefab, transform.position, FirePoint.transform.rotation);
    }
}```
eternal needle
#

it will become clear instantly

hallow acorn
#

oh

#

dont even need it

eternal needle
#

you probably want to only call this once, like in awake or start

hallow acorn
#

yeah

#

thanks a lot

#

it always takes a bit haha

raw token
# glossy turtle there is an array of gameobjects and i am checking if all int values are same li...

You'll need to obtain references to your script components by using GetComponent<MyScript>() on each game object. From the component reference, you will be able to access whatever public members you have declared in your MonoBehaviour class.

Because GetComponent() has some overhead, it is generally a good idea to cache all of the references in another collection if this is something you will be doing often. Or just use a list or array of your MonoBehaviour type to begin with (e.g. public MyScript MyScripts[];), such that your code needn't call GetComponent() at all.

A simple means to test for equality would be to store the first value in a local variable, then loop over the subsequent items checking their value against the first.

glossy turtle
#

i know but its not working.

#

this code is in other class.

#

if (top[i].GetComponent<changedtop>().top==1)
{
countcanvas.count = changechars.Length;
}

raw token
eternal falconBOT
raw token
#

For short snippets such as this, you can surround them with
```cs
YourCode.Here();
```
to make it a little easier for others to read:

YourCode.Here();
raw token
glossy turtle
raw token
# glossy turtle thats a simple programming but i am confused here. let me say i am checking all ...

Sure, I believe I understand your intention for the most part - though I'm not sure what you mean by "its end or its not end."

Is

countcanvas.count = changechars.Length;

only supposed to occur if all of them have the same value? If so, does "it's not working" mean that it's happening even when you don't want it to?

I won't code the solution for you, but if you show more of what you have done already we'll get you there. Namely, the loop. Words can be vague, but code is concise (or I guess we aspire to it being such :P).

quartz nimbus
#

Hi im just curious but what type of code would you generally use to make a player respawn after dying or getting destroyed. Essentially the player/object get destroyed to show that it has died but at the respawning phase I dont know what code to use and I have looked at forums but none have help thus far so just wondering if anyone new it here.

eternal needle
quartz nimbus
#

the when i press player it just takes me to the camera view of the player

#

or am i being stupid

glossy turtle
eternal needle
# quartz nimbus The player is already pre-spawned in the world

if you need to actually spawn the whole object again, Instantiate it then from like a prefab of the player. Though I do find it weird if you're destroying the whole object, cameras and whatever else included. Im not really sure what you mean by the lines below tbh

raw token
quartz nimbus
glossy turtle
eternal needle
quartz nimbus
#

so i can just disable the obj which would be much easier

eternal needle
#

many tutorials are complete shit

quartz nimbus
#

and alot dont help

#

ok thanks for the help so just disabling the obj is easier than destroying in reference to respawning

eternal needle
quartz nimbus
eternal needle
quartz nimbus
raw token
# glossy turtle any same value.

Gotchya 👌

This is roughly the approach I was alluding to above

bool allMatch() {
  // Cache the first value for comparison to the others.
  int firstValue = gameObjects[0].GetComponent<MyScript>().someValue;

  // We already know the first value - start checking from the second.
  for (int i = 1; i < gameObjects.Length; i++) {
    // If this item's value doesn't match the first, they're not all equal - we can return here.
    if (gameObjects[i].GetComponent<MyScript>().someValue != firstValue)
      return false;
  }

  // If the loop completed successfully, all values match.
  return true;
}

But if you're doing this frequently, you really should store the component references somewhere so you're not constantly calling GetComponent()

topaz mortar
#

Why is my game not crashing when this goes over the max allowed int? It just returns 2147483641
int total = Mathf.FloorToInt(value * _multiplier + _offset);

#

is it because _multiplier is a float?

north kiln
#

put it in a checked block if you want to get exceptions for it

#

floats also don't, and just go to infinity

topaz mortar
topaz mortar
#

"In an unchecked context, the operation result is truncated by discarding any high-order bits that don't fit in the destination type."
so it would be capped?

north kiln
#

There is no way to fit anything bigger than MaxInt into an int.

#

So, it follows the documented behaviour in those links

eternal needle
#

small nerd point, its not the number you wrote. its 2147483647, ends in 7

topaz mortar
#

well I just copied the value I was getting 😛 the docs do say it removes the bit, so that might cause the number to a bit different

burnt vapor
#

Pun intended?

weak talon
#

this is the material in inspector
then this is what it looks like in game

why is it so dark in game?

slender nymph
#

lighting presumably. but this is a code channel

weak talon
slender nymph
#

yeah if you don't have lighting in the scene that would be why. that appears to be a lit material.
also #🔎┃find-a-channel

weak talon
fierce geode
#

Why are there two definitions of duration in the SplineContainer class

#

except ones deprecated and one isnt

eager spindle
#

unity things

fierce geode
#

and the only difference is that ones only a getter and the other one is a getter and setter

eager spindle
#

theres a whole layer of depercated things that can inconvenience you

eager spindle
# weak talon oh, how can i make it not a lit material

the opposite of a Lit material is an Unlit material.
every material has a Shader assigned to it; the Shader decides what the object looks like. e.g. a Lit material makes it look like the objecth as lighting, and Unlit material doesnt take lighting into account.
to change a Lit material to an Unlit material, select the material. go to the Shader field below the name of the material. search for an Unlit material.

pastel idol
#

hey guys, I have a problem where UI closes itself when I click on specific point somewhere in the middle. What could cause it?

#

I'm out of ideas, im debugging it 2nd day now

burnt vapor
#

It's not possible to be helped unless you share the relevant code for this

eternal falconBOT
languid spire
fierce geode
#

It feels a bit weird that you can access the NavMeshAgent class and reference in code; but you still have to install the package for Unity to actually use it.

slender nymph
#

NavMeshAgent is still part of the core engine, it's the NavMeshSurface and some other related components that are part of the AI Navigation package. of course that isn't really a code issue though so idk why you're bringing it up in here

pastel idol
# burnt vapor Is it because you click the laptop again by accident?

about the code - I made it only possible to exit by clicking escape button

        if (isLaptopActive && Input.GetKeyDown(KeyCode.Escape))
        {
            ExitLaptopScreen();
        }

    void ExitLaptopScreen()
    {
        isLaptopActive = false;
        laptopUI.SetActive(false);
        mainCamera.gameObject.SetActive(true);
        laptopCamera.gameObject.SetActive(false);

        Cursor.lockState = CursorLockMode.Locked; // Lock the cursor
        Cursor.visible = false; // Hide the cursor
    }```
fierce geode
burnt vapor
#

Should be displayed on top of the method but this might vary per editor

pastel idol
#

thats the only reference

languid spire
burnt vapor
#

I would assume it's somehow still called, yes

pastel idol
#

so it would be an issue with raycast or I messed up something within UI ?

burnt vapor
#

Seems unlikely it closes in a way where it also hides the cursos and all that without being a bug

#

Perhaps the background accidentally has an onclick listened to call the method?

pastel idol
#

nope

pastel idol
languid spire
pastel idol
#

both in method and in if statement

languid spire
#

so, there must be other code also doing this

pastel idol
#

other part of code controlling cursor is this

  void ToggleLaptopScreen()
  {
      isLaptopActive = !isLaptopActive;
      laptopUI.SetActive(isLaptopActive);
      mainCamera.gameObject.SetActive(!isLaptopActive);
      laptopCamera.gameObject.SetActive(isLaptopActive);

      if (isLaptopActive)
      {
          Cursor.lockState = CursorLockMode.None; 
          Cursor.visible = true; 
      }
      else
      {
          Cursor.lockState = CursorLockMode.Locked; 
          Cursor.visible = false; 
      }
  }
#

and it's called after

 if (Input.GetMouseButtonDown(0))
 {
     Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
     RaycastHit hit;

     if (Physics.Raycast(ray, out hit))
     {
         if (hit.transform == transform)
         {
             ToggleLaptopScreen();
         }
     }
 }
languid spire
#

that looks promising, put a debug in there

languid spire
pastel idol
#

I think it's not it

#
void ToggleLaptopScreen()
 {
     Debug.Log("call ToggleLaptopScreen method");

     isLaptopActive = !isLaptopActive;
     laptopUI.SetActive(isLaptopActive);
     mainCamera.gameObject.SetActive(!isLaptopActive);
     laptopCamera.gameObject.SetActive(isLaptopActive);

     if (isLaptopActive)
     {
         Debug.Log("isLaptopActive true");
         Cursor.lockState = CursorLockMode.None;
         Cursor.visible = true; 
     }
     else
     {
         Debug.Log("isLaptopActive false");
         Cursor.lockState = CursorLockMode.Locked; 
         Cursor.visible = false; 
     }
 }

after UI closed it called "isLaptopActive false"

languid spire
#

yes, but should you be doing the raycast at all if isLaptopActive is true. It makes no sense to do that if the UI is displayed

pastel idol
#

you mean raycast can hit laptop when UI is open?

languid spire
#

yes

pastel idol
#

is that even possible?

slender nymph
#

why wouldn't it be

languid spire
#

of course, there are 2 kinds of raycasters, phisics for GO's and Graphics for UI

pastel idol
#

oh really

pastel idol
slender nymph
#

Physics.Raycast can only detect (3d) colliders

#

nothing else blocks it

quartz nimbus
#

Hi so i just made this respawn script but now every time I spawn into the game It causes my cam to move towards the Respawn manager and I dont know why does anyone know how to fiix this issue

pastel idol
#

@languid spire I fixed it by adding if (Physics.Raycast(ray, out hit) && isLaptopActive == false) thank you vm you saved my game

languid spire
pastel idol
#

alright, will do

hallow acorn
#

do i cause an infinite loop? my editor always gets stuck on application.enterplaymode and after 15 minutes i used my task manager and lost 2 hours progress. this time i saved before entering playmode and i still get stuck bc of this part: ``` time -= Time.deltaTime;
int totalTime = Mathf.RoundToInt(time);
while(totalTime > 0)
{
text.text = totalTime.ToString();
}

slender nymph
#

yes, that while loop is an infinite loop

burnt vapor
slender nymph
#

i'm assuming that should really just be an if statement rather than a loop

burnt vapor
#

Considering nothing in this while loop changes totalTime, it probably waits for that

burnt vapor
#

So if this intentional, add a delay using a coroutine for example

#

Or make it async

hallow acorn
#

why is it so insanely hard to make a simple timer wtf

burnt vapor
#

Depends on what you need of course

hallow acorn
#

how?

burnt vapor
#

C# supports timer classes

#

But I would guess you want to make a Coroutine instead

slender nymph
hallow acorn
burnt vapor
burnt vapor
#

Have an integer that defaults to 5, then have a Coroutine decrement it

hallow acorn
slender nymph
hallow acorn
#

the internet is complicated

burnt vapor
#

If you want it to be even better, save a timestamp that is 5 seconds in the future based on Time.time, and wait until Update passed this value

slender nymph
#

or just >=

hallow acorn
#

oh ok

slender nymph
fierce geode
#

Stupid question incoming.
I'm writing a script to hold NPC conversation Data; originally I just did one script that held the entire conversation including every route via recursion. But I'm currently testing out a new segmented approach where the script only contains one conversation and its responses; with it just pointing/referencing to the next route. Was just wondering if one approach is better than the other or its just really semantics at the end of the day.

I imagine that the segmented approach allows for stuff like looping dialogue, say if you wanted to go back to a previous conversation to repeat something much easier. But the recursive approach does make it easier to see where conversations lead; while the segmented option just points to the object where the script is located.

eternal needle
# fierce geode Stupid question incoming. I'm writing a script to hold NPC conversation Data; o...

I wouldnt call this recursion, more like a directed graph or a tree with 4 child nodes (if you've learned the basics of graph theory). But the segmented approach imo is gonna be way better. You've already brought up the case about a looping cycle, which isnt possible in your first approach. If you need any looping dialogue then immediately you have to choose the 2nd approach.
You can easily make this 2nd approach more readable by using scriptable objects (SO). With SO you can name these assets too so it wouldnt just all be [Talk] (Dialogue Choice)

#

Depending on your coding abilities, you could also make your own visualization for the dialogue flow. Kinda like an animator looking tab which shows how dialogue (which would be an asset from an SO) flows from one to another

fierce geode