#đŸ’»â”ƒcode-beginner

1 messages · Page 268 of 1

covert sinew
#

Since all they are is just empties.

timber tide
#

I like sticking to a static amount of slots because growing inventories of slots is a pain in the butt

#

mostly because of the UI

covert sinew
timber tide
#

Ah, yeah that seems like quite the work

covert sinew
#

Yeah. I'm basically working on a game that would have very shallow elements of games like Spore and LBP (with their drag-and-drop creativity stuff, not the actual mechanics associated with them)

fair steeple
#

How is this ambiguous?

bleak pasture
#

you have a 2nd locomotionstate somewhere probably in your project

fair steeple
#

I was just looking for that but can't find anything

bleak pasture
#

might be from packages/asset you imported ?

fair steeple
#

No imports

#

This is the first time I created anything called "locomotionstate" ever

#

I'll try renaming it to something else

north kiln
#

You likely accidentally duplicated the script

fair steeple
#

Probably, but can't find it

#

It's MovementState now

#

lol

cobalt creek
#
bool match = true;
GameObject[] gos = GameObject.FindGameObjectsWithTag("qualWords");
            
if(gos.Length > 0)
{
    foreach(GameObject go in gos)
    {
        string word = go.GetComponent<TextMeshProUGUI>().text;
        for(int a = 0; a < word.Length; a++)
        {
            if(chars.Contains(word[a]))
            {
                //ok
            }
            else if(!chars.Contains(word[a]))
            {
                //error, set false
                match = false;
            }
        }
    }
}
else if(gos.Length == 0)
{
    Debug.Log("you win");
}
            
if(match == true)
{
    //delete word
}
else if(match == false)
{
    // do nothing
}
``` is there way i can shorten this? i made a word search algorithm from list of words gos and the current word to be compared chars. if list has elements, there are more words to find otherwise u win round. the For loop iterate such taht each letter in selected word in word list must be contain in chars variable
#

it also assume match is true until condition that letter not found in chars

wintry quarry
cobalt creek
#

thank

wintry quarry
#

you also don't need == true

north kiln
#

you also don't need to for-loop over characters when you can use a foreach

wintry quarry
#

You can also just use a foreach loop for the loop over the chars in the word

#

jinx

cobalt creek
#

ok

north kiln
#

and you should also break if you don't match

#

instead of continuing to check the remaining characters

wintry quarry
#

Also this: if(gos.Length > 0) is unecessary

#

since the foreach will simply iterate 0 times if it's length is 0

cobalt creek
#

that make sense

#

thank to both i will keep this in mind

ionic juniper
#
 private void Update()
        {
            _sprite.flipX = GameManager.Instance.GetPlayer().GetFlipX();
        }

guys why this is showing an error ?

wintry quarry
#

The only thing that could be null on the indicated line, naturally

#

_sprite

ionic juniper
#

but how is it null

using UnityEngine;
using System.Collections;

namespace my.UndeadSurvival2d.Character
{
    public class CharacterBehaviour : MonoBehaviour
    {
        public bool isFacingLeft = default;
        private SpriteRenderer _sprite;

        protected void Start()
        {
            _sprite = GetComponentInChildren<SpriteRenderer>();
        }

        public void Flip()
        {
            isFacingLeft = _sprite.flipX = !_sprite.flipX;
        }

        public bool GetFlipX()
        {
            return _sprite.flipX;
        }
    }
}

wintry quarry
#

Why are you showing this script

#

It's irrelevant

#

It's null because it was never assigned or because it was assigned to null

#

This is the script with the error

#

Why'd you delete it lol

ionic juniper
#

by mistake omg

#

wait

#

now it's fine

rocky gale
ionic juniper
#

so how _sprite is null ?

wintry quarry
static bay
wintry quarry
wintry quarry
#

It waits for the next frame after the elapsed time

rocky gale
#

so what should i use

wintry quarry
#

So it will wait that amount of time+ however long until the next frame

rocky gale
#

oh makes sense

wintry quarry
# rocky gale so what should i use

Wait one frame at a time and add deltaTime to a timer. When your timer reaches the desired interval, subtract the interval and add a cookie

rocky gale
#

i add deltatime to the timert in while loop?

wintry quarry
#

Yes

rocky gale
#

ok thx

static bay
#

No not while loop.

wintry quarry
ionic juniper
wintry quarry
#

Yes in the while loop đŸ€”

ionic juniper
#

is it an asset

#

missing asset?

wintry quarry
#

It's a Component

#

You don't seem equipped with the basics of how Unity works yet...

#

I recommend following !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ionic juniper
static bay
#

I saw a class with the name AbilitySO.

ionic juniper
static bay
#

Oh you're following a tutorial exactly.

north kiln
#

You're going to need to understand what a SpriteRenderer is and how to add components to continue

wintry quarry
static bay
#

I was just surprised because if you're messing with ScriptableObjects you should have a handle of the basics.

ionic juniper
rocky gale
north kiln
wintry quarry
ionic juniper
static bay
#

Not an asset.

wintry quarry
#

Good luck on that search!

north kiln
#

There is no asset, you haven't added a component to the hierarchy that you're trying to use GetComponentInChildren on

rocky gale
wintry quarry
#

Wherever you need it

rocky gale
#

oo

#

thx

rocky gale
wintry quarry
#

You have it always adding 1 cookie per interval

#

So it's 1 / interval

rocky gale
#

yea but im gonna add more

#

like you can get multiple

wintry quarry
#

So then cookiesAdded/interval

#

The code you shared had 1 so I answered for 1

rocky gale
#

but how do i get the cookies aded tho

#

ik it was mb

wintry quarry
#

You tell me

rocky gale
#

ifk im thinkimg

wintry quarry
#

Presumably you have a variable for it

rocky gale
#

yes

wintry quarry
#

Then use that variable

rocky gale
#

but i have o get how mabny is added in a second no?

wintry quarry
#

(interval is cooldown in the code btw)

rocky gale
#

idk what to do with the. variable thats what im thinking

wintry quarry
#

Wdym? You don't know what to do with which variable?

rocky gale
#

cookiesaddeed variable

wintry quarry
#

In what context

#

When adding cookies you do cookies += cookiesToAdd;

#

When calculating cookies per second you do cookiesToAdd / cooldown

rocky gale
#

ok ill try

sonic dome
#

is there a way i can directly play a animation like
adding a private animation clip name
then something like
name.play?

wintry quarry
sonic dome
#

okk let me try also is there something thing wrong with it that its legacy now?

#

is it advisable?

wintry quarry
#

It's fine

#

Just not as full featured

sonic dome
#

yea thanks works

buoyant horizon
#

!IDE

eternal falconBOT
queen adder
#

why cant I add tag. I saved it and nothing changes..

#

nvm

jaunty oasis
#

Hi every one I am making a game in unity, and I used public TextMeshPro textMesh; // Référence au composant TextMeshPro to reference a texmeshpro3D object in my scene, I referenced it but when I start the game It says "textmeshprocomponent not found" but there is a textmesh pro component, and if I play it and I reference it when it is still playing now it works, why ?

#

And I have TMP essential ressources

#

this isn't textmeshpro ui

#

If someone have time to help me I can give him a tip of 2$ on paypal for the time

slender nymph
#

sounds like your variable is null and you probably need to just assign a proper reference to it

jaunty oasis
#

Yes i done it but I still dont works

slender nymph
#

prove it

jaunty oasis
#

Ok wait

#

we can see it is referenced on the right pannel

slender nymph
#

show the !code

eternal falconBOT
gaunt ice
#

duplicate script?

jaunty oasis
gaunt ice
#

log the value in awake

jaunty oasis
#

I start and it dosent works

slender nymph
#

100% calling GetComponent instead of using the serialized value

jaunty oasis
rare basin
#

you don't need GetComponent if you dragged the reference from the inspector

#

it's overriding what you've dragged

jaunty oasis
#

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

public class PizzaAddedIngredientstext : MonoBehaviour
{
public PlayerController playerController; // Référence au script PlayerController
public TextMeshPro textMesh; // Référence au composant TextMeshPro

void Start()
{
    // Récupérer le composant TextMeshPro attaché à cet objet
    textMesh = GetComponent<TextMeshPro>();

    // Vérifier si le composant TextMeshPro est trouvé
    if (textMesh == null)
    {
        Debug.LogError("TextMeshPro component not found on object: " + gameObject.name);
    }
}

void Update()
{
    // Vérifier si la référence au PlayerController est définie
    if (playerController != null && textMesh != null)
    {
        // Vérifier si c'est une assiette
        if (playerController.heldPlate != null)
        {
            // Récupérer la liste des ingrédients ajoutés
            List<string> ingredientsList = playerController.addedIngredients;

            // Vérifier s'il y a des ingrédients dans la liste
            if (ingredientsList.Count > 0)
            {
                // Construire le texte des ingrédients
                string ingredientsText = "Ingrédients :\n";
                foreach (string ingredientName in ingredientsList)
                {
                    ingredientsText += "- " + ingredientName + "\n";
                }

                // Mettre à jour le texte affiché
                textMesh.text = ingredientsText;
            }
            else
            {
                // Si la liste des ingrédients est vide, afficher un message par défaut
                textMesh.text = "Ajoutez des ingrédients à l'assiette";
            }
        }
rare basin
#

and it's chat gpt code

#

jezus

slender nymph
#

that's exactly what you are doing

jaunty oasis
#

Yep lol

rare basin
#

blindly copy&pasting chat gpt code strikes again

jaunty oasis
rare basin
#

If you want to learn, then don't blidnyl copy&paste the code lol

slender nymph
rare basin
#

"unverfied AI responses" - define unverified

jaunty oasis
#

Ah okk

#

Thx you very much

slender nymph
rare basin
#

yea in his case, but it's not against the rules to seek help with ai generated code in general

rare basin
jaunty oasis
#

trying debuggin

jaunty oasis
slender nymph
jaunty oasis
#

but Ive got just 2€ lol

jaunty oasis
slender nymph
#

yeah and basic logic issues == unverified

jaunty oasis
slender nymph
#

we are not here to fix your AI generated spam

jaunty oasis
#

I'm learning bro

rare basin
#

then learn the proper way

#

instead of spamming clown emotes when someone is trying to help you

#

that's cringe

eternal needle
# jaunty oasis đŸ€Ą

Good way to not get help by anyone, to clown react the people that do help and just say "I'm learning"

jaunty oasis
#

Im the clown I xas saying

#

because you said using chatgpt

rare basin
#

yea sure

jaunty oasis
#

👍

slender cargo
#

Why is this outputting 0 when Happiness is 10, so It should be outputting 0.001?

slender nymph
#

integer math, slap an f on that 1000 to make it a float so you are doing floating point math

slender cargo
#

ahh right

#

But surely because 10,000 isn't a float it doesn't need it?

slender nymph
#

an integer divided by an integer returns an integer

#

1 / 1000 == 0

slender cargo
#

ah I see... Thanks for the help

#

So it was just rounding to the closest integer?

errant canopy
#

Hey I'm trying to disable / enable colliders, but I'm running into an issue of it not working even though I believe it should? My code is here and the issue is on MapSpawning.cs Line 91: https://paste.mod.gg/gynsqcdjapic/3
Any questions or further info you need on my setup in the editor feel free to ask

slender nymph
slender cargo
jaunty oasis
#

Change
private List<GameEventListener> eventListeners = new();
By
private List<GameEventListener> eventListeners = new List<GameEventListener>();

#

In order to change the initialization of the eventListeners list from using C# 9 syntax to the traditional syntax !

slender nymph
#

why

jaunty oasis
#

For the compatibility

#

It is an old feature

teal viper
slender nymph
jaunty oasis
#

ah ok sorry for confusion, he is using 1 / 1000 he need to use 1f /1000

#

or

#

he need to do what I said

#

But because unity is using c#9

#

better using floats

slender nymph
#

you clearly do not understand any of what is going on considering you are now combining two separate issues and giving basically wrong advice regarding them, so perhaps you should focus on learning

tall delta
errant canopy
slender nymph
#

have you ensured that code is running? are there errors? are you certain you are looking at the right object?

teal viper
errant canopy
errant canopy
tall delta
errant canopy
#

Yeah I have and it is

#

I've found a solution now that I think I understand why it was causing issues

eternal needle
errant canopy
#

If I use GetComponentsInChildren<> instead, it will get them all, and since they all spawn in the way the prefab is setup I can just say 1 and 2

wraith valley
#

Hello, who can help me? Button doesn`t work

tall delta
proven junco
#

just got a question abt the rules, like some say ai is not allowed and some say it is allowed after verification?

slender nymph
#

if you have verified that the AI generated code is working and you understand it, then sure. you can get help with your AI generated code. otherwise, no

proven junco
#

oh okay so in theorie somone could just lie abt it

eternal needle
slender nymph
proven junco
#

understandable

wraith valley
# wraith valley Hello, who can help me? Button doesn`t work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{

    public GameObject gameOverCanvas;

    // Start is called before the first frame update
    void Start()
    {
        Time.timeScale = 1;
        gameOverCanvas.SetActive(false);
    }

    public void gameOver()
    {
        GameObject canvas = Instantiate(gameOverCanvas);
        canvas.transform.position = transform.position + new Vector3(540, 1170, 0);
        canvas.SetActive(true);
        Time.timeScale = 0;
    }

    public void PlayButton()
    {
        SceneManager.LoadScene(0);
    }
    // Update is called once per frame

  
    void Update()
    {

    }
}
eternal needle
proven junco
proven junco
#

but when it comes to videos where I "missed" something I come for help

eternal needle
#

In your case you definitely wouldnt wanna use it

proven junco
#

but I'll deff learn programming after this

#

seems veeerry fun

#

but I'd probb do c++

eternal needle
#

There is absolutely no way you will be able to jump straight to c++, ESPECIALLY with AI code. If you're using it as a shortcut now, you arent gonna stop later to learn properly.

tall delta
# proven junco just got a question abt the rules, like some say ai is not allowed and some say ...

I agree it’s a bit ambiguous, I believe the difference is intent / effort. It’s fine to not understand stuff when you are learnining, that’s kind of the point of this chat.
The issue is just when someone with 0 interest / patience to understanding the code, has prompted their way in to code/concepts that are way above their head. And THEN ask people here to fix it. Because you can’t reasonably help them learn since they skipped chapter 1-17, and right on to chapter 18. So the only thing you can really do (and what most of them expect) is to just fix the code for them
 and why would anyone want to do that.

proven junco
#

I'm a great learner and it seems very fun so I see no problem

eternal needle
#

All I have to say is goodluck with that. My previous messages still stand

proven junco
rocky lava
#

im making an enemy patrol around using waypoints, but the field of vision i attached to him does not turn, it want to make it so that if the enemy looks left, the box moves to be left (so infront), does anyone know how to do this?

twilit pilot
rocky lava
gilded elm
#

hi, the goal of my code is that when I place the RAM in the right slot, the object turns green for 5s then it resumes its base material, except that I have the impression of the countdown running not, and green turns on for 1 second and the white function is activated

public MeshRenderer meshRenderer;
public float Rebours = 5; // countdown

void Start()
{
    gameObject.tag = "RAM";                                                     
}

private void OnTriggerEnter(Collider other)                                     
{
    if(other.tag == "RAM")
    {
        if(Rebours>0)
        {
            Rebours -= Time.deltaTime;
            meshRenderer.material.SetColor("_Color", Color.green);                     
        }
        else
        {
            meshRenderer.material.SetColor("_Color", Color.white);                    
            Rebours = 5;    
        }
    }

}

twilit pilot
rocky lava
#

no, hes essentially looking forward the entire time

rocky lava
#

even if he's walking backwards or going to the left

wraith valley
#

Nothing

#

Creating canva in method gameOver doesn`t work too

twilit pilot
#

you can use it alongside your MoveTowards in a similar way

exotic hazel
#

hey.So i was making my player controller but im facing a problem that the character can climb walls which i do not want

burnt vapor
wraith valley
quiet scaffold
#
    void SpawnAcidicSlimes()
    {
        Instantiate(AcidicSlime, new Vector2(SpawnPos1, SpawnPos2), Quaternion.identity);
    }

how do i properly assign an area for the enemies to spawn? i made 2 empty game objects, bottom left and top right

burnt vapor
#

Then take the xy of both and determine the top left and bottom right points

#

Then take a coordinate in the final square

#

If you take the top right then you also got the upper coordinate. Combine that with the left most coordinate of the bottom left and you will have the top left for example.

proven junco
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;


public class PauseMenu : MonoBehaviour
{
    public GameObject pauseMenu;
    public static bool isPaused;

    void Start()
    {
        pauseMenu.SetActive(false);
       
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (isPaused)
            {
                ResumeGame();
                print("Resume");
            }
            else
            {
                PauseGame();
                print("Pause");
            }
        }

    }

    public void PauseGame()
    {
        pauseMenu.SetActive(true);
        Time.timeScale = 0f;
        isPaused = true;
        print("Paused");
    }

    public void ResumeGame()
    {
        pauseMenu.SetActive(false);
        Time.timeScale = 1f;
        isPaused = false;
        print("Resumed");
    }
    public void GoToMainMenu()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene("Main menu");
    }

 



}

I am trying to get this menu working and I dont know if it does cuz in unity dosnt work and my mouse is locked to game in build

#

and do I have to have an void for options too? or can I just do like in the main menu where I have the button direct

teal viper
#

And unlock the mouse

teal viper
proven junco
#

imma try somne

exotic hazel
#

i was watching a tutorial and this is exactly whats written then why is it wrong someoen could help?

proven junco
#

locks as fast as I click mouse button

#

and build still the sma

#

sane

#

same

rocky lava
#

does anyone know how to make it stay upright and rotate the box the direction it's moving

tall delta
# rocky lava i've made my enemy patroller rotate with this code but it doesn't go the directi...

fyi, there are cleaner / smarter ways to do this. but if you're now to manipulating rotations, I think this is a nice starting point.

// get a vector that points to the target point
var moveDir = (partolPoints[targetPoint] - transfrom.positon).normalized;

// create a rotation that points to the target point
var rotation = Quaternion.LookRotation(moveDir).eulerAngles;

// set rotation around the y-axis
rotation.x = 0;
rotation.z = 0;

// apply the rotation
transform.rotation = Quaternion.Euler(rotation);```

the problem with the code you have now is that you are just 'rolling' the object along the same 'line' that you are moving
modest quarry
#

im folllowing code monkey's free course and this error pop up

#

this is code of the stove file and i pass in the same parameters but only in 2nd time it error

keen dew
#

christ that line numbering scheme

#

it says the error is on line 54 so fryingRecipeSO is null

#

assuming this is KitchenObject.cs

modest quarry
dim bridge
modest quarry
keen dew
dim bridge
tall delta
modest quarry
modest quarry
#

but not in line 73

keen dew
modest quarry
#

hmm better?

keen dew
#

The object it instantiates doesn't have a KitchenObject component

modest quarry
#

Oh

#

OK i found it

#

tthank u

keen dew
#

Next time when the compiler tells you where the error is, trust what it says. It knows better than you

modest quarry
#

yeah its always right

dim bridge
#

False...

proven junco
#

yo I implementet an "cursorlockstate none if esc key down" in my player controller and it works no problems but Now im trying to have so that when I press the button again it locks

dim bridge
#

Ther error is always right but the line no can be wrong if there some sorta missing ending etc.. (idk why I needed to say this)

ivory bobcat
#

Auto wrap text would still be the same line.

proven junco
#

that I dont know how to lock the cursor

#

I know the code

#

but dont know where to put it or in what place

#

Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;

#

I cant write else { Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;}

#

dosnt work

#

under the if statement

#

so Idk

dim bridge
#

Are you using a boolean variable to tell if the game is paused or not or anything like that

proven junco
#

yeah static bool

#

I'm also trying to lock the curser by pressing the resume game opt no progress

ivory bobcat
dim bridge
#

Ngl I haven't used cursor lock was just checking you weren't doing smth dumb like

if ButtonDown("Menu")
{
}
else
{
}
#

Have you looked at the api page for it

proven junco
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;


public class PauseMenu : MonoBehaviour
{
    public GameObject pauseMenu;
    public static bool isPaused;

    void Start()
    {
        pauseMenu.SetActive(false);
       
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (isPaused)
            {
                ResumeGame();
                print("Resume");
            }
            else
            {
                PauseGame();
                print("Pause");
            }
        }

    }

    public void PauseGame()
    {
        pauseMenu.SetActive(true);
        Time.timeScale = 0f;
        isPaused = true;
        print("Paused");
    }

    public void ResumeGame()
    {
        pauseMenu.SetActive(false);
        Time.timeScale = 1f;
        isPaused = false;
        print("Resumed");
   
    }
    public void GoToMainMenu()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene("Main menu");
    }

 



} 

#

then I laid an unlock cursor in my player mov

#
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        }
        else
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
#

wait

#

imma try one

#

in build now

#

changed it up

ivory bobcat
#

Pseudocodecs if button down if pause ... else ... pause = !pause

proven junco
#

well build and cursor not worko

dim bridge
#

Yeah you need to check if its paused when you press the key then determine that

proven junco
proven junco
#

can't I place a lockmouse in pause script

#

I tried but I only got errors

#

or do I need a connection between mov and pause script

spiral narwhal
#

I think you're shooting yourself in the foot in the long run doing it this way.
If you have a pause script, it should be the only script that knows if the game is paused or not. Then you invoke two events, OnGamePause, and OnGameResume that take care of the extra things that should happen, like the time scale

proven junco
#

I have no clue how events works

#

that's the problem

spiral narwhal
#

It's just a normal field like float, bool etc

#

But it's called UnityEvent

#

And then you call Invoke when you want to trigger it

#

i.e. in your pause method

proven junco
#

I tried fifling with it some days ago

#

but it did not go my way

spiral narwhal
#

Try again

#

We'll help you

proven junco
#

how do I start

#

like bool resume game in mov

spiral narwhal
#

Before that though, I joined the convo late. What is the actual problem you have? My issue was just with hardcoding the time scale stuff

dim bridge
#
if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (isPaused)
            {
                //Lock here
                ResumeGame();
                print("Resume");
            }
            else
            {
                //Unlock here
                PauseGame();
                print("Pause");
            }
        }
hidden sleet
#

I've had to sort of brute force this code, as each InventoryItem type has a different object type inside, I wanted to return the name, ideally without needing to check what type it is beforehand, but it was a pain so I just did this. Is it possible to just use some kind of generic method that can retrieve the name regardless of the type? ```cs
private void HandleItemnameRequest(int itemIndex)
{
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
if (inventoryItem != null)
{
if (inventoryItem is InventoryPlainItem)
{
var tempInvItem = inventoryItem as InventoryPlainItem;
inventoryUi.UpdateName(itemIndex, tempInvItem.item.name);
}
else if (inventoryItem is InventoryStructureItem)
{
var tempInvItem = inventoryItem as InventoryStructureItem;
inventoryUi.UpdateName(itemIndex, tempInvItem.item.structureName);
}
else if (inventoryItem is InventoryUniqueItem)
{
var tempInvItem = inventoryItem as InventoryUniqueItem;
inventoryUi.UpdateName(itemIndex, tempInvItem.item.itemName);
}

}

}```

dim bridge
proven junco
dim bridge
#

Its in your code already the comments are where you just put the code for locking and unlocking the mouse

hidden sleet
#

fair point

proven junco
#

oh yeah imma try this

ivory bobcat
hidden sleet
#

And if I want to return the actual item in it, but each item is different, is it possible to create a sort of generic return value for a method, a bit like the getComponent method?

spiral narwhal
# hidden sleet fair point
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
if (inventoryItem != null && inventoryItem is IRequestable requestableItem)  
     inventoryUi.UpdateName(itemIndex, requestableItem.Request());
hidden sleet
#

gotcha

ivory bobcat
spiral narwhal
hidden sleet
#

So considering how each of these have different object types in them - cs public class InventoryStructureItem : InventoryItem { public StructureSerialised item; }

public class InventoryUniqueItem : InventoryItem
{
    public Item item;
}
public class InventoryPlainItem : InventoryItem
{
    public ItemSO item;
}
```, I was hoping to just make a generic GetItem method
hidden sleet
#

and even then, each derived class would have to hold a different item type, which is what I have going on here

proven junco
#

well now it works

#

thx

spiral narwhal
#

Oof, it seems you shot yourself in your own foot with the architecture you have so far.
What is the difference between Item and ItemSO? And what is StructureSerialised

proven junco
#

but now I have to get resume button to lock mouse

#

maybe own script for that

ivory bobcat
dim bridge
hidden sleet
# spiral narwhal Oof, it seems you shot yourself in your own foot with the architecture you have ...

ItemSO is a scriptable object item, so I have predefined a set of items in my assets folder that this could be. Item is generated at runtime and are each wholey unique, made by the player, structureSerialised is essentially a list of gameobjects described by their relative displacement to a group object. Ideally I just wanted one inventory script that I could then get working regardless of the type in the container, or else I'd have several duplicate inventories and would have to rewrite my Ui scripts

dim bridge
spiral narwhal
proven junco
#

yeah started really learning it this week/last

spiral narwhal
#

If so I would have each of them do the work they need to do in the UI

dim bridge
proven junco
#

but I've been on my grind

#

still don't know how to code

dim bridge
#

Did two tutorial videos and made my own small game I finished yesterday as a micro challenge

ivory bobcat
dim bridge
proven junco
#

yeah started with one game

#

yeah I've been on modelling more

#

bc I kinda don't have time to learn coding rn

#

gotta make this game

#

started coding maybe 2 years ago

dim bridge
#

You understand why the locking/unlocking worked in that spot right?

proven junco
#

but I left

#

so I forgot

#

yeah

dim bridge
#

Ok just making sure

#

Copy paste forget is not a great learning strat lol

proven junco
#

I've been picking up things when watching videos on how to do specific things

#

no I had coding in school but I stopped

hidden sleet
#

Well the getname interface works brillirantly at the moment. The main reason why I'm facing issues is say I want to add an item, I'd prefer it if I could just say inventoryContainer.AddItem(AnyItemType item) and it just create the item in the inventory with the correct slot and type

proven junco
#

so I forgot

#

but It is still back there

#

somewhere

#

been picking up things tho when I watch videos

#

on how to do special things

#

then try putting those in others

#

so I have a basic understanding of code

hidden sleet
#

But here for instance, ```cs
private void HandleItemSpawnRequest(int itemIndex)
{
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);

if (true)
{

}

inventoryItem.item.Spawn();
inventoryData.RemoveItem(itemIndex, 1);

}

dim bridge
#

@rich adder how much of a perf hit is referencing a class/object in a script btw bc I'm probably gonna use that a lot more if it isn't hard hitting and I wouldn't think it would be to hard hitting

queen adder
#

I keep getting this error and I have been searching for about 3 days trying to fix this error and it is not working. Apparently, NavMesh agent is not enabled? But I don't know how to enable it cause I can't find anything on Unity or StackOverflow.

#

how do i indent code this is confusing me

ivory bobcat
queen adder
#

It was.

ivory bobcat
#

Floating or missing navmesh can generate this error

queen adder
#

dat scary man is the navmesh agent

#

what if i change the agent type to humanoid?

ivory bobcat
#

Did you generate the nav mesh surface?

queen adder
#

yo

#

i had to change the agent type

#

it works now

#

do i need to fix this or no?

ivory bobcat
#

Eyeball the scene and see if there are two event systems

queen adder
#

there are when i start up the scene

ivory bobcat
#

You'd want exactly one

queen adder
#

how do i fix that?

#

cause it creates one every time the scene starts?

ivory bobcat
#

Get rid of the other event system object

queen adder
#

in the gameover scene there is one

queen adder
ivory bobcat
queen adder
#

no just the one in that scene

#

cause you said delete it

ivory bobcat
#

Before, your warning was suggesting that you had more than one

queen adder
#

huh?

#

in the scene before that one it doesn't have one?

ivory bobcat
#

You'd get similar warnings if you've got two cameras and whatnot - a specific component on the camera.

queen adder
#

oh shit

#

i have a timeline camera

hidden sleet
#

Jsut tried this out - cs public interface IRequestableItem<T> { public T GetItem(); }
With the interface attached to my slot classes ```cs
public class InventoryPlainItem : InventoryItem, IRequestableString, IRequestableItem<ItemSO>
{
public ItemSO item;

public ItemSO GetItem()
{
    return item;
}

public string GetName()
{
    return item.name;
}

}```
But I need to define the type it expects every time I try to use it.

if (inventoryItem is IRequestableItem<ItemSO> requestableItem)
{
    requestableItem.GetItem().Spawn();

}
``` I take it there's no real workaround to make this as generic as possible?
queen adder
#

oh god-

queen adder
gleaming kraken
#

i wonder if i'll actually learn anything from this..

queen adder
#

Try using unity !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

hes cool

queen adder
#

i think i have to recreate the scene

ivory bobcat
queen adder
#

yeah

#

and i deleted it...

#

so i think I need to restart the scene?

#
private void Update()
{ 
    if(dataGroup.justSlide == 0)
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(worldPoint.x, worldPoint.y);
            if (Collider2D.OverlapPoint(touchPos))
            {
                SpriteTouched();
            }
        }
    } else if (dataGroup.justSlide == 1)
    {
        if (Input.touchCount > 0)
        {
            Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(worldPoint.x, worldPoint.y);
            if (Collider2D.OverlapPoint(touchPos))
            {
                SpriteTouched();
            }
        }
    }  
}

This is a script that allows player to drag / slide on a screen to catch pieces instead of clicking multiple times, and it works, but i wanna make it also work on computers, so a player can drag a mouse to fire SpriteTouched instead of click click click you know.
this is the mouse detecting script:

private void OnMouseDown()
{

    if (Input.GetMouseButtonDown(0)) 
    {
        SpriteTouched();
    }
}
queen adder
hidden sleet
marble turret
#

Is there a way to remove items from the right click menu? Like when I click my project folder, and want to create a cs file with the right-click > create function , i have a lot of other options there I will never use. I want to remove those

queen adder
#

i don't think you can do that

marble turret
#

Hmmm, because i have no use for things like materials, they just hide the stuff I do want

queen adder
#

@ivory bobcat it stopped now

#

im able to publish my demo

#

FINALLY

hidden sleet
#

I think I'm going to have rewrite a considerable part of this inventory code...

The get name thing works, but other parts break, now I'm getting to the point where I can't get much new stuff done

hidden sleet
#
public void AddItem(I item, int quantity)
{
    bool isFound = false;
    for (int i = 0; i < inventoryContainer.Count; i++)
    {
        var CurrentSlot = inventoryContainer[i];

        if (CurrentSlot is IRequestableItem<I> requestableItem)
        {
            if (requestableItem.GetItem() == item)
            {

            }

        }``` I'm getting an error in the GetItem line saying I can't perform == on type I and T, I just want to check to see if the current slot contains the same item type as the one passed in, how can I do this?
wintry quarry
minor palm
#

I means infinity in computer language

#

Guys I want some information whenever I download unity install editor it's get failed I have rtx 4060 laptop why is this happening

hidden sleet
#
public interface IRequestableItem<T>
{
    public T GetItem();
}```
In this case T is going to be the inventory item slot, I is the type of item that goes in that slot.
```cs
public class InventorySO<T, I> : ScriptableObject where T : InventoryItem
{
    [SerializeField]
    private List<T> inventoryContainer;
}
public void AddItem(I item, int quantity)
{
    bool isFound = false;
    for (int i = 0; i < inventoryContainer.Count; i++)
    {
        var CurrentSlot = inventoryContainer[i];

        if (CurrentSlot is IRequestableItem<I> requestableItem)
        {
            if (requestableItem.GetItem() == item)
            {
                inventoryContainer[i].ChangeQuantity(quantity + inventoryContainer[i].quantity);
                InformAboutChange();
                isFound = true;
            }

        }
``` If that helps at all
wintry quarry
rocky lava
#

So right now i made all of my interactable objects have a certain value, and i want to make it so when i press f on it (interacts and picks it up (disables gameobjects), it adds to a little counter in the top right

hidden sleet
rocky lava
#

i don't understand how i can make the text on the UI link to the value score

wintry quarry
#

I think you would need to just say where I : class wherever that I type parameter is defined

#

Because right now it can be anything and it's not guaranteed that a struct can be compared with==

#

You need some kind of generic type constraint that ensures I == I is valid
@hidden sleet

#

(note that says I and I not I and T)

hidden sleet
#

although if get item returns type I, and type I is declared above, can it not just use that and check to see if the objects are the same?

acoustic crow
#

!code

eternal falconBOT
wintry quarry
#

if you did this:

public struct Example {
  public int x;
}

void Blah() {
  Example a = new();
  Example b = new();
  bool same = a == b;
}```
It would be a compile error @hidden sleet
#

So you need a type constraint that ensures == is valid between I and itself

#

for example I : class would guarantee == is a valid thing to do.

hidden sleet
#

so even though the item type being returned is I, and the item being passed in is I, that isn't enough to ensure both will be the same

wintry quarry
#

it ensures both are the same type

#

it doesn't ensure you can use == on it

hidden sleet
#

right

#

not sure what class to use for that then

wintry quarry
#

no class

#

just the word class

#

as per my example

hidden sleet
#

oh really? I thought you meant that as a placeholder

wintry quarry
#

not a placeholder

hidden sleet
#
public class InventorySO<T, I> : ScriptableObject where T : InventoryItem where I : class
{``` Ah, that's cleared the error now ```cs
public void AddItem(I item, int quantity) 
{
    bool isFound = false;
    for (int i = 0; i < inventoryContainer.Count; i++)
    {
        var CurrentSlot = inventoryContainer[i];

        if (CurrentSlot is IRequestableItem<I> requestableItem)
        {
            if (requestableItem.GetItem() == item)
            {
                inventoryContainer[i].ChangeQuantity(quantity + inventoryContainer[i].quantity);
                InformAboutChange();
                isFound = true;
            }

        }```
wintry quarry
#

yep!@

hidden sleet
#

I think I follow now

wintry quarry
#

it's just saying "I can be anything as long as it's a class"

#

in other words - it isn't allowed to be a struct

#

and now the compiler is happy that == will always be valid

hidden sleet
#

So if I've said that T extends the InventoryItem class, wherever I use this class i've given it a concrete type, can I make it so I create a new object of the type I pass in, as well as an item?

here for instance, I've got three different possible item slot types, since I've now got T as the slot type and I as the item, is it possible to do a sort of T newSlot = new T?

wintry quarry
hidden sleet
#

I take it this isn't possible? InventoryItem newItemSlot = new T();

#

cause where I use this class I've defined the slot type, and I was hoping to just be able to create a slot of that type in the inventory code itself

wintry quarry
#

it can be - depending on the type constraints.

queen adder
#

I made a prefab for my player mainly because I didn't want to have to remake the player again and now whenever you spawn and move around the capsule doesn't follow you (playeR)

hidden sleet
#

Cause now I pass in the slot type and item i'd like to just be able to add the item slot without having to necessarily define it here

queen adder
wintry quarry
hidden sleet
#

none of these classes have any constructors, so i take it that that's not enough?

wintry quarry
#

because T is not constrained

#

so it can't know that the parameterless constructor exists

buoyant knot
#

for that you can add the new constraint

late bobcat
hidden sleet
#

even if T : InventoryItem? is that not constraining it?

buoyant knot
#

but what if you make Bomb : InventoryItem, and Bomb has no parameterless constructor

#

you would need:
where T : InventoryItem, new()

hidden sleet
#

ah I see

wintry quarry
buoyant knot
#

or what I sometimes do is make a kind of constructor as a non-constructor method in my base class

#

it is unfortunate that C# does not have a thisClass keyword

#

because you can’t make a base class have a function that just outputs the most derived class, for this.

hidden sleet
#

I think I follow

buoyant knot
#

one of my recent classes has:
public abstract NonFungibleTileData CopyAt(Vector2Int pos);
which calls the actual constructor, for the given class implemented

hidden sleet
#

actually hang on

#

so in the actual inventory I can't just add something to the container if it's not the class in the where clause

#

I'm lost again notlikethis

#

So if someone were to have a generic inventory type, how are you supposed to add items to it if creating type T is such a faff

wintry quarry
#

I would say.... that polymorphism is actually a pretty trap and a pitfall, and that inventory items should all just be of one concrete type, which is extensible via composition, rather than inheritance!

#

Anyway if you want to be able to construct the items this will do just fine:
where T : InventoryItem, new()

hidden sleet
hidden sleet
#

how might that work in the context of an inventory? As I've only ever engaged with it conceptually in the Unity component system

vagrant lynx
#

Guys, when I'm pressing W or S player is going backward and forward so, I changed the input manager of Horizontal and vertical to invert and then it worked. But when I implemented the rotation of the player then it was rotating in the opposite direction. What's going on?

hidden sleet
#

Blast, now I'm back to square one, as in doing this I can't get the item ```cs
T newItemSlot = new T();
newItemSlot.item = item as ItemSO;
inventoryContainer.Add(newItemSlot);

I wish I could just rewrite this whole thing again but actually know what I'm doing
wintry quarry
wintry quarry
#

Maybe show your code.

hidden sleet
#

If i were to just stick to one InventorySlot class type, but set the item inside to a generic, do you reckon that would work out better than having multiple slot types?

buoyant knot
#

polymorphism is good, but is also a major noob trap

wintry quarry
#

Probably. Why do you have multiple slot types?

#

I would expect something more like:

[Flags]
public enum ItemType {
  Consumable,
  Equipment,
  Quest
}

public class InventorySlot {
  public Item item;
  public ItemType allowedItemTypes;
}```
buoyant knot
#

novices will spam polymporphism where inappropriate, leading to big issues.
More experience leads to a lot less inherittance, followed by using the tool a medium amount when you know what you are doing.

wintry quarry
#

that's how I would probably restrict slots to hold certain items

hidden sleet
vagrant lynx
# wintry quarry Maybe show your code.

float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 moveDir = new Vector3(h, 0f, v);

    if (moveDir.magnitude >= 0.1f)
    {
        float target = Mathf.Atan2(moveDir.x, moveDir.z) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, target, 0f);
        cc.Move(moveDir * speed * Time.deltaTime);
    }
#

cc is character controller

hidden sleet
wintry quarry
#
            float target = Mathf.Atan2(moveDir.x, moveDir.z) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Euler(0f, target, 0f);
            moveDir = transform.rotation * moveDir;
            cc.Move(moveDir * speed * Time.deltaTime);```
buoyant knot
hidden sleet
#

I think I've probably fallen into the inheritance trap then

buoyant knot
#

eg:
For Circle, inherit from Shape.
For getting area, use IAreaGetter.
For an object with multiple shapes, make List<Shape>

hidden sleet
#

let me try and draw up a quick diagram so I can make my current setup more clear, and see what I'm messing up concepcually

rocky lava
#

Whenever my scenemanager finishes the game and it goes back to the main menu, my mouse is locked and not visible, how do i make it so that i can only use it in the main menu and when it goes back to the main game it locks again?

wintry quarry
#

make sure you're setting it as appropriate

rocky lava
#

this is the level complete script, would i put it here?

wintry quarry
buoyant knot
hidden sleet
#

This is a pretty simple explanation of what I've got going on. The InventoryItem (just picture that as an inventory slot) only has the quantity, then derived classes contain the unique types. At first I assumed this was the way to go, but do you reckon that's the wrong approach now?

buoyant knot
#

what is a structure item

#

i don’t think that is too bad, but I suspect an interface would work here

hidden sleet
#

A list of coordinate positions and objects, describing how various objects are positioned relative to a group object, basically a structure in the game, a list of parts

public class StructureSerialised : ISpawnable
{
    public string structureName;
    public List<StructurePartData> StructurePartList = new List<StructurePartData>();
}
buoyant knot
#

remember that an interface can request getters.

#

public interface Item {
public int number {get; }
}

hidden sleet
hidden sleet
buoyant knot
#

so the interface does not define the field, but can define that you need to be able to go get something of that property

#

which is usually tied to a field

#

remember that inheritance comes with baggage

hidden sleet
#

I believe I might have something somewhat similar to that in the slot classes

buoyant knot
#

baggage is good if you are just going to repeat that same implementation exactly in multiple classes

vagrant lynx
hidden sleet
#

So the way i've done the slots isn't necessarily bad?

#

It's just at the moment it's being a nuisance and won't let me create the derived slot objects to then add to the inventory, so I'm wondering if there's a way for me to just have one slot class and the rest happen from that

rocky lava
#

Whats the word i make it unlocked with? i have this right now but Unlocked or UnLocked both dont work

hidden sleet
#

unfocused I believe

hexed terrace
#

delete the . then type it again .. your intellisense will show you what can go there

wintry quarry
#

or yes intellisense

rocky lava
#

it was CursorLockMode.none

hidden sleet
#

One thing that's still confusing me, before I get some much needed lunch, is that I've got this line up top saying it extends this class, so why is it that later on when I want to create a new object that derives from that class, it says it can't convert to T. If what I want to make derives from the class, why does it not accept it?

wintry quarry
#

but it doesn't say which derived class it is

hidden sleet
#

Yeah so if it’s expecting T to derive, I don’t fully understand why it’s throwing a fit when I give it what it expects

acoustic crow
#

!code

eternal falconBOT
wintry quarry
#

then InventoryPlainItem would not fit

#

The compiler does not know that you actually have checked the type dynamically here

#

it's not smart enough

#

What you can do is force a cast

#

Add((T)newItemSlot);

#

or the safest:

if (newItemSlot is T t){
  inventoryContainer.Add(t);
}```
stone pilot
hidden sleet
wintry quarry
#

it doesn't know that it's the same derived class that was chosen as T

hidden sleet
#

Ah, I see

wintry quarry
#

It's not smart enough to infer that from your if (thing is Type) code

#

it could be but it isn't.

hidden sleet
#

So in my case, I want to make the derived object, set the item, then add that to this list, so I just need to manually check that the type is actually the type T is meant to be

wintry quarry
stone pilot
hidden sleet
#

I can manage ugly for the time being, just want to get it working

wintry quarry
hidden sleet
#

Once I’ve finished this project I’ll just start the next one and try to avoid the same mistakes

stone pilot
#

alr

stone pilot
woven crater
#

how do i make the particle that arl created not moving along with the object?

hidden sleet
swift crag
#

you'll find this at the top of the particle system's inspector

woven crater
#

nice got it

stone pilot
wintry quarry
#

My guess is isDashing is never being set back to false

stone pilot
#

alright ima check it

wintry quarry
# stone pilot alright ima check it

Likely because:


    private void HandlePlayerDeath()
    {
        isRespawning = true;
        Instantiate(deathParticlePrefab, transform.position, Quaternion.identity);
        gameObject.SetActive(false);
        Invoke("RespawnPlayer", respawnDelay);
    }```
You are setting the GameObject to be deactivated here
#

so if you are depending on a coroutine or Invoke to set isDashing to be false, that will fail when it's deactivated

#

it's also pretty unclear to me how your respawn is working since you're deactivating the object.

hidden sleet
#

After making these changes i've found that the inspector now asks for some InventorySO'2 reference, but I've never called anything that before

glad sundial
#

How do I make a walkie-talkie using Photon Voice?

wintry quarry
swift crag
#

Yes, the grave is used to denote a generic tpye.

#

This means that the type needs two generic type parameters.

#

I'm mildly surprised that actually serialized at all

hidden sleet
#

ah

swift crag
#

actually, i'm more than mildly surprised. Can you show us the relevant code?

hidden sleet
#

that makes sense since I've introduced some generic types

#

although now it won't take my inventory as a valid type

#

and now I can't create the scriptable object at all

swift crag
#

Show us the code.

hidden sleet
#

I have a feeling that maybe scriptable objects don't work with this?

wintry quarry
#

they will but with generic types it becomes complicated

#

you need to make your own editor tooloing to actually make instances of them

hidden sleet
#

oh goodness

swift crag
#

You can't create an instance of an InventorySO<T, I> without actually providing type parameters

#

which I presume is what Unity attempts to do here

hidden sleet
#

blast

swift crag
wintry quarry
swift crag
#

interesting -- I didn't know that was even possible. I would expect Unity to not be able to record the generic types you used to create that specific asset

hidden sleet
#

so in this case, would it just be better to simply avoid using scriptable objects and just make the inventories as is?

wintry quarry
wintry quarry
hidden sleet
#

gotcha

swift crag
hidden sleet
#

SOs have worked quite well for me so far

wintry quarry
#

you've got yourself tied in a frustrating knot here unfortunately

hidden sleet
hidden sleet
swift crag
#

Is there a good reason for this to be generic at all?

#

Whoever uses this object will need to be aware of its type parameters too

hidden sleet
swift crag
#

You can't just have a List<InventorySO> or something

#

Okay, so you did intend to have something like

[SerializeField] InventorySO<SomeItemKind, SomeItemClass> someItems;
[SerializeField] InventorySO<OtherItemKind, OtherItemClass> otherItems;
#

You can just subclass InventorySO once for each kind of item you need

#
public class SomeInventorySO : InventorySO<SomeItemKind, SomeItemClass> { }
#

much like what you have to do to use generics elsewhere

hidden sleet
# swift crag Okay, so you did intend to have something like ```cs [SerializeField] Inventory...

I've got a set of controllers that would hold a reference to one of these inventories so i can change their contents and whatnot ```cs
public class RawInventoryController : MonoBehaviour
{
[SerializeField] UiInventoryPage inventoryUi;
[SerializeField] public InventorySO<InventoryUniqueItem, Item> inventoryData;
//Try to make this non public later
private void Start()
{

    PrepareInventoryData();
    PrepareUi();
}

/// <summary>
/// During update, look through every key value pair in the dictionary that maps an index to an item.
/// Update the ui to match the item index, quantity and name
/// </summary>
private void Update()
{
    foreach (var item in inventoryData.idToItem())
    {
        inventoryUi.UpdateData(item.Key, item.Value.quantity, item.Value.itemName);
    }
}

/// <summary>
/// Will create empty ui slots, then listen to the Ui's click methods
/// </summary>
private void PrepareUi()
{
    inventoryUi.InitInventoryUi(inventoryData.GetInventorySize());
    inventoryUi.onItemSpawnRequested += HandleItemSpawnRequest;
    inventoryUi.onItemCraftRequested += HandleItemCraftRequest;
    inventoryUi.onItemNameRequested += HandleItemnameRequest;
}

private void HandleItemCraftRequest(int itemIndex)
{
    InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
}

private void HandleItemSpawnRequest(int itemIndex)
{
    InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
    if (inventoryItem is IRequestableItem<Item> requestableItem)
    {
        requestableItem.GetItem().Spawn();
        inventoryData.RemoveItem(itemIndex, 1);

    }

    
    

    /* Other solution:
     * ISpawnable spawnableItem = inventoryItem.item as ISpawnable
     * spawnableItem.spawn*/
}

/// <summary>
/// Clear inventory data. Sets a listener to update the ui whenever the inventory is changed
/// </summary>
private void PrepareInventoryData()
{
    inventoryData.Init();
    inventoryData.OnInventoryChanged += UpdateInventoryUi;
}

/// <summary>
/// Update the Ui to match the inventory model
/// </summary>
/// <param name="inventoryState">Key value pairs of the inventory model</param>
private void UpdateInventoryUi(Dictionary<int, InventoryUniqueItem> inventoryState)
{
    // Clear the inventory completely, then update the Ui to match the dictionary
    inventoryUi.ResetAllItems();
    foreach (var item in inventoryState)
    {
        if (item.Value is IRequestableString requestableItem)
        {
            inventoryUi.UpdateData(item.Key, item.Value.quantity, requestableItem.GetName());
        }



    }
}

private void HandleItemnameRequest(int itemIndex)
{            

    InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
    if (inventoryItem != null && inventoryItem is IRequestableString requestableItem)
        inventoryUi.UpdateName(itemIndex, requestableItem.GetName());
}

}```

#

at this point though I'm open to any alternatives

swift crag
hidden sleet
#

I just wanted to have a base inventory that lets me add items, remove items, get items and whatnot regardless of the type of item, or else I'd be repeating myself

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

public class Movement : MonoBehaviour
{
    public Transform movePos;
    [SerializeField]private float speed;
    private bool up,down,left,right;
    private Animator anim;
    private SpriteRenderer sr;
    [SerializeField]private Sprite s_up,s_down,s_left,s_right;

    void Awake()
    {
        anim = GetComponent<Animator>();
        sr = GetComponent<SpriteRenderer>();
    }
    void FixedUpdate()
    {
        Move();
        Look();
    }
    void Move()
    {
        transform.position = Vector2.MoveTowards(transform.position,movePos.position,speed * Time.deltaTime);
        if(Input.GetKey(KeyCode.S))
        {
            up = false;
            down = true;
            left = false;
            right = false;
            anim.SetBool("down",true);
            anim.SetBool("up",false);
            anim.SetBool("left",false);
            transform.rotation = Quaternion.Euler(0f, 0f, 0f);
            if(transform.position == movePos.position)
            {
                movePos.position += new Vector3(0,-1);
            }
        }

        else if(Input.GetKey(KeyCode.W))
        {
            up = true;
            down = false;
            left = false;
            right = false;
            anim.SetBool("up",true);
            anim.SetBool("down",false);
            anim.SetBool("left",false);
            transform.rotation = Quaternion.Euler(0f, 0f, 0f);
            if(transform.position == movePos.position)
            {
                movePos.position += new Vector3(0,1);
            }
        }
        else if(Input.GetKey(KeyCode.D))
        {
            up = false;
            down = false;
            left = false;
            right = true;
            anim.SetBool("left",true);
            anim.SetBool("down",false);
            anim.SetBool("up",false);
            transform.rotation = Quaternion.Euler(0f, 180f, 0f);
            if(transform.position == movePos.position)
            {
            movePos.position += new Vector3(1,0);
            }
        }
        else if(Input.GetKey(KeyCode.A))
        {
            up = false;
            down = false;
            left = true;
            right = false;
            anim.SetBool("left",true);
            anim.SetBool("down",false);
            anim.SetBool("up",false);
            transform.rotation = Quaternion.Euler(0f, 0f, 0f);
            if(transform.position == movePos.position)
            {
                movePos.position += new Vector3(-1,0);
            }
        }
        else
        {
            anim.SetBool("down",false);
            anim.SetBool("up",false);
            anim.SetBool("left",false);
        }
    }

    void Look()
    {
        if(up)
        {
            sr.sprite = s_up;
        }
        else if(down)
        {
            sr.sprite = s_down;
        }
        else if(right)
        {
            sr.sprite = s_left;
        }
        else if(left)
        {
            sr.sprite = s_left;
        }
    }
}

can anyone tell me why the sprite renderer isnt working?

wintry quarry
hidden sleet
#

because a unique item is a completely separate class, not just a label for a base item class

wintry quarry
#

what's different about it

#

what are all the differences?

swift crag
#

this is a common problem in inventory systems

hidden sleet
#

bear with me

wintry quarry
swift crag
#

you either:

  • create one item class that is very flexible. the type system can't stop you from making an item that's unique, yet also has a stack count of 1000
  • create many item classes that are very specific. now you have type hell, with is keywords everywhere.
sonic dome
wintry quarry
sonic dome
wintry quarry
#

is the animator also setting the sprite?

sonic dome
wintry quarry
sonic dome
#

but i tried this

        if(!anim.GetBool("down") && !anim.GetBool("up") && !anim.GetBool("left"))
        {
            if(up)
            {
                sr.sprite = s_up;
            }
            else if(down)
            {
                sr.sprite = s_down;
            }
            else if(right)
            {
                sr.sprite = s_left;
            }
            else if(left)
            {
                sr.sprite = s_left;
            }
        }
wintry quarry
#

also 4 different bools is crazy

#
            else if(right)
            {
                sr.sprite = s_left;
            }```
#

đŸ€” đŸ€” đŸ€” đŸ€” đŸ€”

sonic dome
sonic dome
rare basin
#

dictionary<direction,sprite> @sonic dome

wintry quarry
sonic dome
rare basin
#

dictionary? google it

#

you can change all that 4 else/if into 1 line

sonic dome
swift crag
#

A dictionary lets you store a key with a value.

rare basin
#

sr.sprite = spritesDictionary[direction]

sonic dome
#

let me try

hidden sleet
# wintry quarry what are all the differences?

ItemSO - What you'd consider the classic item for game inventories. There are a set pool of possible items I define in the assets folder.

    [CreateAssetMenu]
    public abstract class ItemSO : ScriptableObject, ISpawnable
    {
        public bool isStackable;
        public int Id;
        public string Name;
        public GameObject prefab;

        public abstract void Spawn();
        
    }
}```
Item - Generated at runtime based on labels that the user assigns, therefore I can't determine the possible items before running.
```cs
public class Item 
{ 
    public GameObject objectPrefab;
    public string itemName;
    public Image sprite;
    public Color color;
    public string mainLabel;
    public List<string> descriptionLabels;
}

StructureSerialised - A list of gameobjects connected to an empty node, described by local coordinate positions to allow for file saving and spawning. Created by the player at runtime too.

public class StructureSerialised : ISpawnable
{
    public string structureName;
    public List<StructurePartData> StructurePartList = new List<StructurePartData>();

    public void Spawn()
    {
        Debug.Log("Structure Spawned");
    }
}

These are the three possible item types. Each inventory will only hold one type, but I wanted a system where I could just have one inventory script that handles adding items, removing items, getting the index of items etc without being concered with what type is passed in.

But any attempt to do so has been painful. Leading to all this

#

I'm open to any other ways of doing this, even if it means another rewrite

#

So I suppose I could either stick to SOs but have 3 different inventory types, or move to regular classes and have to learn how to maintain inventories between scenes

#

Which is why I've then got a generic type here, for instance. ```cs
public class InventorySO<T, I> : ScriptableObject where T : InventoryItem, new() where I : class
{
[SerializeField]
private List<T> inventoryContainer;

#

At the start of the day I did only have one controller, but after introducing the generic types I split it into 3 so I could have the types assigned properly. ```cs
public class RawInventoryController : MonoBehaviour
{
[SerializeField] UiInventoryPage inventoryUi;
[SerializeField] public InventorySO<InventoryUniqueItem, Item> inventoryData;
//Try to make this non public later
private void Start()
{

    PrepareInventoryData();
    PrepareUi();
}

/// <summary>
/// During update, look through every key value pair in the dictionary that maps an index to an item.
/// Update the ui to match the item index, quantity and name
/// </summary>
private void Update()
{
    foreach (var item in inventoryData.idToItem())
    {
        inventoryUi.UpdateData(item.Key, item.Value.quantity, item.Value.itemName);
    }
}```
#

so if you have any other preferred ways of doing this, I'm all ears

#

Might bring out the sketch book and try to draw up the problem

hidden sleet
stoic glen
#

Why doesn't the object rotate around the player? It feels like the player should be more right then he is.

[SerializeField] private Transform player;
[SerializeField] private GameObject MoveObject;

void Update()
    {
        Vector3 playerPos = player.position;
        Vector3 playerLook = player.forward.normalized;
        int x_Look = Mathf.RoundToInt(playerLook.x);
        int z_look = Mathf.RoundToInt(playerLook.z);
        Vector3 objctPosition = new(playerPos.x + x_Look, MoveObject.transform.position.y, playerPos.z + z_look);
        MoveObject.transform.position = objctPosition;
    }```

Or is there another reason then the code?
swift crag
#

you're rounding to whole numbers here

#

playerLook is a normalized vector, so its length is 1

#

you're only going to get -1, 0, or 1 out of those rounding operations

wintry quarry
stoic glen
#

When he looks rigth, the object should be on his rigth side

swift crag
#

why not just do player.position + player.forward, then?

#

that would position the object one meter in front of the player

wintry quarry
#
Vector3 relativePosition = new(0, 0, 1);
MoveObject.transform.position = player.TransformPoint(relativePosition);```
@stoic glen
swift crag
#

If you want it to snap to a grid, you'd need to do the rounding after computing objectPosition anyway, since the player's position isn't snapped to a grid

quartz mural
#

can anyone explain

wintry quarry
quiet scaffold
#

How can I properly play audio if an enemy gets hit/dies? I can add an AudioClip + AudioSource component on the Enemy.cs class, but it isnt placed anywhere, I only derive from there, so I can never assign the AudioClip + AudioSource for it to work?

https://hastebin.skyra.pw/elupededak.csharp

swift crag
wintry quarry
quartz mural
#

firs time using a dictionary

swift crag
#

and what is the context for this? Show the entire script.

#

If you put this in the wrong place, the parser will have no idea what's going on and give you a ton of errors

quartz mural
#

if i do that

#

i wont fit

#

so ill show whats relevant

wintry quarry
#

!code

eternal falconBOT
swift crag
#

No, you'll show the entire script.

swift crag
quartz mural
#
public int HP {  get; set; }

public List<Move> Moves {  get; set; }
public Dictionary<Stat, int> Stats { get; private set; } //Stores its key(Stat) along with value(int)
public Dictionary<Stat, int> StatBoost { get; private set; }

public void Initialisation()
{

    // Generate Moves
    Moves = new List<Move>();
    foreach (var move in Base.LearnableMoves)
    {

        if (move.Level <= Level)
            Moves.Add(new Move(move.Base));

        if (Moves.Count >= 4)
            break;
    }

    CalculateStats();
    HP = MaxHp;

    StatBoost = new Dictionary<Stat, int>();
    {
        {Stat.Attack, 0},
        {Stat.Defense, 0},
        {Stat.SpAttack, 0},
        {Stat.SpDefense, 0},
        {Stat.Speed, 0},
    };
}

void CalculateStats()
{
    Stats = new Dictionary<Stat, int>();
    Stats.Add(Stat.Attack, Mathf.FloorToInt((Base.Attack * Level) / 100f) + 5);
    Stats.Add(Stat.Defense, Mathf.FloorToInt((Base.Defense * Level) / 100f) + 5);
    Stats.Add(Stat.SpAttack, Mathf.FloorToInt((Base.SpAttack * Level) / 100f) + 5);
    Stats.Add(Stat.SpDefense, Mathf.FloorToInt((Base.SpDefense * Level) / 100f) + 5);
    Stats.Add(Stat.Speed, Mathf.FloorToInt((Base.Speed * Level) / 100f) + 5);

    MaxHp = Mathf.FloorToInt((Base.MaxHp * Level) / 100f) + 10;
}

int GetStat(Stat stat)
{
    int startVal = Stats[stat];
    //stat boost

    return startVal;
}

public int Attack
{
    get { return GetStat(Stat.Attack); } //Calcualtes stats from base stats and level (actual formulas used in game)
}

public int Defense
{
    get { return GetStat(Stat.Defense); }
}

public int SpAttack
{
    get { return GetStat(Stat.SpAttack); }
}

public int SpDefense
{
    get { return GetStat(Stat.SpDefense); }
}

public int Speed
{
    get { return GetStat(Stat.Speed); }
}

public int MaxHp
{
    get; private set;
}
swift crag
eternal falconBOT
wintry quarry
swift crag
wintry quarry
#
StatBoost = new Dictionary<Stat, int>();```
swift crag
#

which was very important

polar acorn
swift crag
#

Very precise, yes.

quiet scaffold
#

don't wanna spam but
How can I properly play audio if an enemy gets hit/dies? I can add an AudioClip + AudioSource component on the Enemy.cs class, but it isnt placed anywhere, I only derive from there, so I can never assign the AudioClip + AudioSource for it to work?

https://hastebin.skyra.pw/elupededak.csharp

swift crag
#

Then, for each enemy prefab, you can assign references.

stone pilot
#

hey @wintry quarry i've done this and its still not working

    {
        isRespawning = true;
        Instantiate(deathParticlePrefab, transform.position, Quaternion.identity);
        pl.isDashing = false;
        pl.canDash = false;
        sp.enabled = false;
        Invoke("RespawnPlayer", respawnDelay);
    }

    private void RespawnPlayer()
    {
        transform.position = spawnPosition.position;

        gameObject.SetActive(true);

        isRespawning = false;

        pl.isDashing = true;
        pl.canDash = true;
        sp.enabled = true;
    }```
wintry quarry
polar acorn
swift crag
burnt vapor
swift crag
#

which will explode your players' ears

wintry quarry
swift crag
#

(and make the audio crap out)

wintry quarry
quiet scaffold
#

if my game is 2d, do i just put 0,0,0 for the position?

burnt vapor
quiet scaffold
#

of AudioSource.PlayClipAtPoint

#

cause it requires a position?

polar acorn
#

You pass in the position you want the sound to play at

burnt vapor
#

It's not going to play the sound globally, just at the position

quiet scaffold
#

ah

swift crag
#

2D audio doesn't get panned, does it?

quiet scaffold
#

I guess I'll just play it on my players position so it sounds global

swift crag
#

If the sound is supposed to be in-world, you should play it at the correct position so that it gets quieter as you get further away

#

e.g. the sound of an enemy being hit

hidden sleet
#

Bout to go and take a break for the day, one more question about the inventory thing, since it's not really going to work out given how I've implemented it at the moment, do you feel I should just simplify it and make separate inventory scripts for each and be done with it?

swift crag
#

the sound of gaining points would not be positioned in the world

quiet scaffold
#

I want it to play globally when you hit/kill an enemy, putting it on my players position would probably work fine?
but I've come into another problem because prefabs are a problem for me;
I can't attach my players prefab in to the public GameObject Player space of my enemy prefab, it just wont let me drag it on, and if i select it from my scene, it says Type Missmatch

nvm fixed it

glad sundial
#

How do I make a walkie-talkie using Photon Voice?

grizzled zealot
#

Are the update() methods on GOs called in sequence on a single thread or are they called in parallel?

grizzled zealot
polar acorn
#

You could convert the whole project over to DOTS

#

which is also still not parallel but closer to it

grizzled zealot
ripe shard
quartz mural
grizzled zealot
carmine turret
#

Just doing some theory crafting, when it comes to AI vision I see people making comes of raycast, but wouldn't it be more realistic and also better on processing to do one raycast per eye (if you're going for realism to the player, of if you want even hands to be viable, instead do a raycast to the widest 4 positions on the player

#

Would this not be better than a cone of raycasts, but more realistic than a single raycast?

#

(checking the ais face direction and any obstacles of course)

wintry quarry
#

The tradeoff is realism vs complexity and performance.

timber tide
#

Raycast is smol

rocky canyon
#

soo, you cant copyright systems, methods, or ideas, but you can copyright the code written.. as its considered a literary work..
and asset store agreement forbids redistribution of ALL assets that use default license.. but say I started with a system and It's been sooo heavily modified its not even the same code anymore.. that would still forbid me from sharing a project containing reminants of said code-base..

soo i'd just have to re-write it from scratch. w/o any of the code i used as template

edit: even if the code is basic functions that i'd re-use in my own version.. (it would end up looking very similar)

wintry quarry
#

1 raycast smol.
infinite raycasts beeg

stoic glen
#

Both, the player and the cube, have the same x and z coordinates, why are they that far away. Every other object has the same coordinates like the cube.

wintry quarry
rich adder
rocky canyon
#

performance is a whole different beast.. and usually a later step in development..

#

if needed at all

rocky canyon
#

yup, I wrote a little helper component that displays world transform

stoic glen
#

Is there a away to create something like folders, that it's more organisted

stoic glen
wintry quarry
#

The project window?

#

The Heirarchy of the scene?

stoic glen
rocky canyon
#

if you had an empty gameobject at 0,0,0 / and put all ur player stuff under it.. world and local coords would be identical for example

dim bridge
rocky canyon
wintry quarry
rocky canyon
#

-Audio-- --Lighting-- and --DDOL--- are all organizational gameobjects

#

ya, empty gameobjects are great to organize. (can disable to hide big bulks of ur game not needed while u develop)

#

keep em at 0,0,0 and u shouldn't have any issue.. if they do become an issue using transform.localPosition, etc can be helpful

rocky canyon
#

i usually dont nest my player tho.

rich adder
rocky canyon
#

its usually more for props, lighting, effects, etc

rocky canyon
stoic glen
rocky canyon
#

odds are you wont.. unless ur code is just nasty af

rich adder
#

you get more performance hit with high poly models đŸ„Č

rocky canyon
#

but a player i usually keep root level just to avoid any issues that may appear

rocky canyon
#

funny b/c i am artist -> game-dev

#

but game-dev made me rethink using high detail graphics everywhere..

rich adder
rocky canyon
#

i'll keep those reserved for my blender renders llol

#

look at these high-details

rich adder
#

mortal poly count

rocky canyon
#

as an asset user and a creator it sucks trying to keep things uniform

rich adder
#

had a mesh the other day, 700K tris đŸ˜”â€đŸ’«

rocky canyon
#

some low poly models have HIGH detail textures.. some high poly models have LOW detail textures.. some in the middle some LODs some not..

#

is a headache.. soo if i have to build more stuff than i can salvage.. imma model in low detail

#

can always pop a default material on high detail models to pretend they're lower quality

rich adder
#

I use the same material on decimated mesh it looks just as good for my usecase

#

I usually make ps1-style game now anyway

rocky canyon
rocky canyon
#

like mspaint pallate ;D

#

less advanced materials == less lighting work i have to do

rich adder
#

yeaaaaa thats the shite i like

rocky canyon
#

me too but i havent been able to do it yet

#

need a good shader first

#

one with vertex wobble lol

rich adder
#

yeah the closest i found finally works on URP

rocky canyon
#

đŸ„ł

#

URP shaders are hard to comeby sometimes

#

im still hunting a good Outline shader

#

that isn't SS

rocky canyon
flint falcon
#

when i start up unity i keep getting this error code. tried reinstalling and updating all my drivers. Assertion failed on expression: 'SUCCEEDED(hr)'

rich adder
#

oh my shader im using might be the same

rocky canyon
#

figured he'd just give some general tips

glad sundial
#

How do I make a walkie-talkie using Photon Voice?

flint falcon
#

lmao thats what i thought!

rocky canyon
#

theres no more to that error @flint falcon

#

? can u show screenshot of console

#

@flint falcon update ur drivers

flint falcon
#

yeah I tried that

rocky canyon
#

all of em? even windows?

#

no icon?

rich adder
rocky canyon
#
i had the same problem i checked the drivers following Thomasthom suggestion and they where all up to date but i noticed i had 2 display adaptors an intel HD graphics one and an nvidia one so i concluded that unity was using the intel one that didnt suport DX11 so i disabled the intel so it would definitively use the nvidia
the screen flickered and changed settings winch i changed back then opened unity and voila it worked
i guess unity doesn't play well with laptops that use intel HD graphics to save power
note tat doing this will negatively impact battery so reactivate intel HD graphics after you use unity```
#

apparently you get a white-screen-of-death

#

lol

flint falcon
#

this time it freaked out shut off monitors and i got this

rich adder
#

Oh yeah issue with your GPU

rocky canyon
#

ur GPU seems to be struggling

#

make sure its not trying to use ur integrated graphics

#

unless thats all u have.. and then.. you may just have to do what u can

rich adder
#

either gpu drivers are crashing somehow or yeah you might be pushing it to its apparent limits

rocky canyon
#

update ur graphics card 🙂

#

or revert to a driver that works

flint falcon
rocky canyon
#

yea, may have to play with teh drivers a bit

#

try a good restart

rich adder
flint falcon
#

yeah just updated them

rich adder
#

the nvidia ones not the microsoft ones

flint falcon
#

yup same

rocky canyon
#

so geforce is happy?

rich adder
#

have you tested other games / 3d applications

flint falcon
#

geforce is happy

#

do i need to make sure its using my 4070 and not something else?

rich adder
#

ideally

#

if you have integrated make sure ur GPU is used instead

flint falcon
#

where might do that? in unity or in launcher?

rocky canyon
#

device manager

flint falcon
#

ok now it will start but still the error for Assertion failed on expression: 'SUCCEEDED(hr)'

rocky canyon
#

that error seems to have many different solutions

whole idol
#

WTF are all these?

rocky canyon
#

errors

hexed terrace
#

Warnings

whole idol
#

why?

rich adder
flint falcon
whole idol
#

yeh but what kind of errors?

rocky canyon
#

Warning Errors

#

its about shaders/ URP

#

the rendering pipeline

rich adder
# whole idol why?

There are too many Package Manager dependencies to list, stopping after 100

whole idol
#

not sure what that means

rocky canyon
#

lol.. try restarting.. /rebuilding the Library folder

flint falcon
#

how do I check which graphics card im using?

rocky canyon
#

find ur project folder. and inside you'l find a Library folder.. delete that and restart ur project in unity.. it'll take a bit longer it'll rebuild ur library

#

fix meta files and whatnot

whole idol
#

of the specs

rocky canyon
#

CPU-X

summer stump
#

Task Manager

rich adder
#

speccy n ccleaner are spyware

summer stump
whole idol
rocky canyon
polar acorn
flint falcon
rich adder
summer stump
rocky canyon
rich adder
#

nope

summer stump
flint falcon
#

i know which one i have

rocky canyon
flint falcon
#

its new

rich adder
flint falcon
#

but this error keeps popping up

#

Assertion failed on expression: 'SUCCEEDED(hr)'

rocky canyon
#

okay lol

burnt vapor
rocky canyon
#

My secondary monitor was plugged into directly the motherboard. Pluging it into my videocard instead solved the issue.

whole idol
#

@flint falcon alternatively you can try HWInfo

rich adder
# rocky canyon jeezus

for the most part windows knows how to take care of itself, I just use something like spacesniffer to delete the TEMP garbage

rocky canyon
#

theres 100s of solution for that error nicky..

flint falcon
#

lol greaty

rocky canyon
#

not sure which one fits u

rich adder
#

most of those "OS cleaners " are spamm

flint falcon
#

c an i just leave it there?

rocky canyon
#

if it doesn't bother u

#

just clear the consoel

burnt vapor
rich adder
#

agreed

rocky canyon
#

i use it to clean my old registry keys

#

not sure how to do that by hand

rich adder
#

just go to the folder and delete them

#

registry is just fancy folders

rocky canyon
#

yea, but its like decyphering the rosetta stone

#

which ones? idk

rich adder
#

you're coding games!

rocky canyon
#

đŸ€«

rich adder
#

no way registry is harder

rocky canyon
#

i'll give it a shot

rich adder
#

type regedit and ur golden

rocky canyon
#

ya, i know how to get there.. just not what to do lol

#

@flint falcon is this a URP/HDRP project?

#

its 100% graphics card related

#

this solution has come up the most often

#

and try to reinstall ur graphics card

rocky canyon
#

nope... not today

rich adder
rocky canyon
#

hahahah.. i mean could be fax..

#

it does show keys i remember deleting already lol

#

give us something good CR7

crisp sand
#

https://gdl.space/jijoqiwaqu.cs. im having an error and i dont know why its happening, i think im making a reference to everything but it seems to not be the case ( the link is for the other(and longer) script)

rocky canyon
#

aww, disappointed

rocky canyon
#

whats on line 28 of SelectionManager.cs?

polar acorn
rich adder
#

oh there is a link :

rocky canyon
#

lol me too

polar acorn
#

Yeah the link is to SelectionManager and the image is InteractableObject