#đ»âcode-beginner
1 messages · Page 268 of 1
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
Yeah, I managed to get it working, since an "infinite" inventory was really important for my game, due to my plans for it to revolve around crafting so heavily.
Ah, yeah that seems like quite the work
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)
How is this ambiguous?
you have a 2nd locomotionstate somewhere probably in your project
I was just looking for that but can't find anything
might be from packages/asset you imported ?
No imports
This is the first time I created anything called "locomotionstate" ever
I'll try renaming it to something else
You likely accidentally duplicated the script
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
well you should learn to just use else you don't need an else if for just the opposite case
thank
you also don't need == true
you also don't need to for-loop over characters when you can use a foreach
ok
and you should also break if you don't match
instead of continuing to check the remaining characters
Also this: if(gos.Length > 0) is unecessary
since the foreach will simply iterate 0 times if it's length is 0
private void Update()
{
_sprite.flipX = GameManager.Instance.GetPlayer().GetFlipX();
}
guys why this is showing an error ?
It's null.
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;
}
}
}
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
https://hastebin.com/share/oligeruhay.csharp how do i get cookies gained per second
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
so how _sprite is null ?
Well with that code, you don't, because the way you're adding cookies isn't going to be consistent over time.
GetComponentInChildren isn't finding a SpriteRenderer
Already answered #đ»âcode-beginner message
how
WaitforSeconds isn't precise
It waits for the next frame after the elapsed time
so what should i use
So it will wait that amount of time+ however long until the next frame
oh makes sense
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
i add deltatime to the timert in while loop?
Yes
ok thx
No not while loop.
Or it's not running at all @ionic juniper
how can i ensure that it took SpriteRenderer?
there is no SpriteRenderer file ig
Yes in the while loop đ€
File? What?
It's a Component
You don't seem equipped with the basics of how Unity works yet...
I recommend following !learn
:teacher: Unity Learn â
Over 750 hours of free live and on-demand learning content for all levels of experience!
i'm following tutorial i just need to fix it
I saw a class with the name AbilitySO.
yes
Oh you're following a tutorial exactly.
You're going to need to understand what a SpriteRenderer is and how to add components to continue
You probably missed something in the tutorial. Go back and make sure everything is the same. And not just the code. The setup in the scene too
I was just surprised because if you're messing with ScriptableObjects you should have a handle of the basics.
bro i'm not game developer i just want to fix it lol
like this?
yield return null;
timer += Time.deltaTime;
if (timer >= cooldown)
{
timer -= cooldown;
CookieClick.cookies++;
}
Yes
You seem to be trying to do a lot of game development for someone who refuses to learn any game development then
And then 1/cooldown is your cookies per second.
i will try to find the missing asset
Not an asset.
Good luck on that search!
There is no asset, you haven't added a component to the hierarchy that you're trying to use GetComponentInChildren on
in the if timer >= cooldown part?
wait but it doesnt take into account the cookies getting added after said interval
Wdym
You have it always adding 1 cookie per interval
So it's 1 / interval
You tell me
ifk im thinkimg
Presumably you have a variable for it
yes
Then use that variable
but i have o get how mabny is added in a second no?
Just told you how
(interval is cooldown in the code btw)
idk what to do with the. variable thats what im thinking
Wdym? You don't know what to do with which variable?
cookiesaddeed variable
In what context
When adding cookies you do cookies += cookiesToAdd;
When calculating cookies per second you do cookiesToAdd / cooldown
ok ill try
is there a way i can directly play a animation like
adding a private animation clip name
then something like
name.play?
If you use the legacy Animation component
okk let me try also is there something thing wrong with it that its legacy now?
is it advisable?
yea thanks works
!IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
âą Visual Studio (Installed via Unity Hub)
âą Visual Studio (Installed manually)
âą VS Code
âą JetBrains Rider
âą Other/None
true
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
Yes i done it but I still dont works
prove it
show the !code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
duplicate script?
log the value in awake
I start and it dosent works
100% calling GetComponent instead of using the serialized value
where
you don't need GetComponent if you dragged the reference from the inspector
it's overriding what you've dragged
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";
}
}
Ah possible
that's exactly what you are doing
Yep lol
blindly copy&pasting chat gpt code strikes again
I am learning, I saw reviews on serialized value but i didn't understood
If you want to learn, then don't blidnyl copy&paste the code lol
it is against server rules to seek help with AI generated code. #đâcode-of-conduct
well not really
"unverfied AI responses" - define unverified
i mean, they clearly didn't verify it
yea in his case, but it's not against the rules to seek help with ai generated code in general
where should we send our paypals
nope I verified several times
trying debuggin
I tryed add you on discord
and that's why there were no issues, right?
It arrives sometimes stupids errors
yeah and basic logic issues == unverified
đ€Ą
we are not here to fix your AI generated spam
I'm learning bro
then learn the proper way
instead of spamming clown emotes when someone is trying to help you
that's cringe
Good way to not get help by anyone, to clown react the people that do help and just say "I'm learning"
yea sure
đ
Why is this outputting 0 when Happiness is 10, so It should be outputting 0.001?
integer math, slap an f on that 1000 to make it a float so you are doing floating point math
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
there's no rounding involved. it's how many times the second number fits inside the first. 1000 cannot fit in 1 so the result is 0
ahh right, Learn something new every day
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 !
why
How do you know that it's not working?
that is entirely unrelated to their issue. also latest unity uses c# 9
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
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
not sure if it's related as I cba to parse the whole file, but I see that in the other cases you are accessing element '1', and in the issue case you're looking at element '0'. could that be the problem?
I see in the Inspector that the colliders don't get enabled.
have you ensured that code is running? are there errors? are you certain you are looking at the right object?
Then it doesn't. Did you debug where you enable/disable it?
Ah yeah that's a mistake, but not relevant as I don't hit those 2 if cases since the 2 triggers don't get enabled
Yes, and I see that the child / parent relationship is correct and all the children have the BoxCollider component which are still set to false.
first off, have you tried to just add a debug.log to make 100% the relevant part of the code is actually being executed?
Yeah I have and it is
I've found a solution now that I think I understand why it was causing issues
Smells like another AI response..
currentSpawnedMapItems[0].SectionObject.GetComponentsInChildren<BoxCollider>()[1].enabled = true;
currentSpawnedMapItems[0].SectionObject.GetComponentsInChildren<BoxCollider>()[2].enabled = true;
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
Hello, who can help me? Button doesn`t work
jesus... is that actually a thing? not only do we have AI questions, but also AI responses đ
just got a question abt the rules, like some say ai is not allowed and some say it is allowed after verification?
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
oh okay so in theorie somone could just lie abt it
Well it's just someone asking chatgpt the question someone asked here. Then they paste it, while clearly not knowing the basics.
people do all the time. and every single time it is annoying as fuck
understandable
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()
{
}
}
It's not really about lying, but a beginner using AI code is very obvious because they dont understand any of it or why it does/doesnt do something. Someone who knows what they're doing realistically would use AI to type code that they just dont wanna type.
it is probb so much harder then helping someone that actually have some kind of understanding abt the code
oh yeah, I try to solve ai codes with ai and mostly works
but when it comes to videos where I "missed" something I come for help
In your case you definitely wouldnt wanna use it
yeah, I would want to actually do all coding for myself but I got no time and ai has been a big up this project
but I'll deff learn programming after this
seems veeerry fun
but I'd probb do c++
#đ»âcode-beginner message
Well when you get to an error, you can pretty much guarantee you're gonna be stuck in a world of spaghetti.
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.
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.
no like soon I will need to be done with this project and actually have time to learn things, then I will go from the absolute begging in c++
I'm a great learner and it seems very fun so I see no problem
All I have to say is goodluck with that. My previous messages still stand
yeah for sure, I might not have the biggest understanding to code but while I "skip" steps I try atleast to understand or get some kind of understanding on how and what I'm doing, for be then later be able to spot other problems
Help please
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?
try disabling other canvases in your scene & check if the button works without them
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;
}
}
}
are you not turning your enemies at all?
no, hes essentially looking forward the entire time
I have 1 canva
even if he's walking backwards or going to the left
there's a few ways to handle rotations, a simple way is: https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
you can use it alongside your MoveTowards in a similar way
hey.So i was making my player controller but im facing a problem that the character can climb walls which i do not want
Weird, good luck with your issue
EventSystem doesn`t work too
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
Those two gameobjects define the bounds of the area?
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.
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
Use a different key for testingđ€·ââïž
And unlock the mouse
No clue what you're trying to say here.
yeah second thing just forget it
imma try somne
i was watching a tutorial and this is exactly whats written then why is it wrong someoen could help?
I tried unlocking the mouse but no progress
locks as fast as I click mouse button
and build still the sma
sane
same
i've made my enemy patroller rotate with this code but it doesn't go the direction it's moving, and it spins around very weirdly
does anyone know how to make it stay upright and rotate the box the direction it's moving
it worked got it fixed
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
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
Self Destory.. đ
christ that line numbering scheme
it says the error is on line 54 so fryingRecipeSO is null
assuming this is KitchenObject.cs
no error in in this line
I just noticed that wtff is going on there...
this file is stovecounter
Is it counting based on the selected line..
not a fan of vim motions I take it đ
look here i used that Spawnkitchenobject same function in line 57 it works
but not in line 73
Now you managed to cut the line numbers off completely
hmm better?
The object it instantiates doesn't have a KitchenObject component
Next time when the compiler tells you where the error is, trust what it says. It knows better than you
yeah its always right
False...
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
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)
Auto wrap text would still be the same line.
What's the issue?
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
Are you using a boolean variable to tell if the game is paused or not or anything like that
yeah static bool
I'm also trying to lock the curser by pressing the resume game opt no progress
Break the problem down. Determine when/how-often a button is pressed.
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
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
Pseudocodecs if button down if pause ... else ... pause = !pause
well build and cursor not worko
Yeah you need to check if its paused when you press the key then determine that
yeah no clue what that does mean
Or when pausing rather
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
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
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
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
if (Input.GetKeyDown(KeyCode.Escape))
{
if (isPaused)
{
//Lock here
ResumeGame();
print("Resume");
}
else
{
//Unlock here
PauseGame();
print("Pause");
}
}
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);
}
}
}```
@proven junco this should work
where should I put this
Its in your code already the comments are where you just put the code for locking and unlocking the mouse
An interface
fair point
oh yeah imma try this
If they're mono behaviours, you can access the name property. If not, use an interface to enforce a related common property to acquire the name.
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?
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
if (inventoryItem != null && inventoryItem is IRequestable requestableItem)
inventoryUi.UpdateName(itemIndex, requestableItem.Request());
gotcha
Maybe you ought to consider not placing unrelated items into a single list/array. Else you'll have to parse if you're wanting to return an explicit type without using generic. Otherwise lookup generic methods with c#.
Wouldn't all items be of an item class or at least extend an item class
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
in this case they are all so different I couldn't really have them all extend a base item class
and even then, each derived class would have to hold a different item type, which is what I have going on here
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
What do you mean by "GetItem"? The explicit derived type?
You could make the method public and use the same script on the button although idk might be messy depending on whats all serialized
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
I will say Im Im new to Unity myself
I see. And you only need to "Get" these item types to render them in the UI?
yeah started really learning it this week/last
If so I would have each of them do the work they need to do in the UI
About the same for me
Did two tutorial videos and made my own small game I finished yesterday as a micro challenge
Else returning the base type would be a breeze. You'd then have the base provide the necessary methods and derived class' implement them.
This is where we part ways
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
You understand why the locking/unlocking worked in that spot right?
I've been picking up things when watching videos on how to do specific things
no I had coding in school but I stopped
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
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
But here for instance, ```cs
private void HandleItemSpawnRequest(int itemIndex)
{
InventoryItem inventoryItem = inventoryData.GetItemAt(itemIndex);
if (true)
{
}
inventoryItem.item.Spawn();
inventoryData.RemoveItem(itemIndex, 1);
}
@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
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
Is the agent active? Was it properly placed on a generated nav mesh?
It was.
Floating or missing navmesh can generate this error
Did you generate the nav mesh surface?
Eyeball the scene and see if there are two event systems
there are when i start up the scene
You'd want exactly one
Get rid of the other event system object
in the gameover scene there is one
it worked but now whenever i click the go back button it doesn't work
Did you accidentally remove all event system objects? You need one to have ui interaction
Before, your warning was suggesting that you had more than one
There are two event systems in the scene. Please ensure there is always exactly one event system in the scene.
You'd get similar warnings if you've got two cameras and whatnot - a specific component on the camera.
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?
oh god-
do i recreate event system and put event system script in it?
i wonder if i'll actually learn anything from this..
Try using unity !learn
:teacher: Unity Learn â
Over 750 hours of free live and on-demand learning content for all levels of experience!
i mean i used brackeys
hes cool
thats how this game was made
i think i have to recreate the scene
You need an event system object if you're wanting to interact with the ui elements
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();
}
}
yo whenever i go to the game over scene there is 2 event systems
you can just create it in the same menu as anything else
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
i don't think you can do that
Hmmm, because i have no use for things like materials, they just hide the stuff I do want
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
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?
We would need more context. Like what is I and T and the definition of IRequestableItem
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
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
Show the full error message?
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
i don't understand how i can make the text on the UI link to the value score
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)
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?
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no, as I said, there's no guarantee I == I is valid
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.
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
oh really? I thought you meant that as a placeholder
not a placeholder
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;
}
}```
yep!@
I think I follow now
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
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?
This case is actually specifically mentioned here! https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#unbounded-type-parameters
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
it can be - depending on the type constraints.
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)
What constraints would cause an issue?
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
you would need to constrain it to a type that ensures there's a parameterless constructor
none of these classes have any constructors, so i take it that that's not enough?
it doesn't know what class it is
because T is not constrained
so it can't know that the parameterless constructor exists
for that you can add the new constraint
guys do you know what could be causing the lines to appears when i move my character?
even if T : InventoryItem? is that not constraining it?
but what if you make Bomb : InventoryItem, and Bomb has no parameterless constructor
you would need:
where T : InventoryItem, new()
ah I see
ah yeah I forgot you can do new() as a type constraint
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.
I think I follow
one of my recent classes has:
public abstract NonFungibleTileData CopyAt(Vector2Int pos);
which calls the actual constructor, for the given class implemented
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 
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
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()
Haven't read too much into composition, but as I understand it, isn't it like the object component system, where you sort of add functionality in bits to create something instead of inheriting?
yes exactly
how might that work in the context of an inventory? As I've only ever engaged with it conceptually in the Unity component system
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?
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
well you pretty much described it. The main class would just have the things common to all inventory items (name, sprite/image, weight? value?) etc.
Then it'd have a list of something like ItemExtraData instances.
Anything special like "equipment stats" would be represented in this list, which could be subclasses of ItemExtraData for example
Why did you invert your input manager axes?
What problem are you trying to solve?
Maybe show your code.
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?
polymorphism is good, but is also a major noob trap
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;
}```
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.
that's how I would probably restrict slots to hold certain items
Well in my mind I thought initially that I'd have one base slot type, and then since I had different types of items where each were different, that making different slots would work
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
So I'd probably just replace Item with a generic
you're not rotating moveDir according to the rotation of the character
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);```
inheritance for when you need to exact replicate an implementation to all children, which are of the type.
composition when you just need to have the tools.
interface when you just need to expose a specific set of outward methods
I think I've probably fallen into the inheritance trap then
eg:
For Circle, inherit from Shape.
For getting area, use IAreaGetter.
For an object with multiple shapes, make List<Shape>
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
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?
Cursor.lockState
make sure you're setting it as appropriate
I would unlock the cursor in Start in a script in the main menu.
I would lock the cursor in Start in a script in the game scene
to answer inheritance vs composition vs interface:
- Do you need to inherit an implementation or field?
NO => interface - Given yes, do you want to inherit ALL the implementations and fields?
Yes => inherit
No => composition
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?
what is a structure item
i donât think that is too bad, but I suspect an interface would work here
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>();
}
remember that an interface can request getters.
public interface Item {
public int number {get; }
}
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I did not know that
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
I believe I might have something somewhat similar to that in the slot classes
baggage is good if you are just going to repeat that same implementation exactly in multiple classes
Thanks for this bro, it fixed the rotation
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
Whats the word i make it unlocked with? i have this right now but Unlocked or UnLocked both dont work
unfocused I believe
delete the . then type it again .. your intellisense will show you what can go there
Check the docs: (scroll to bottom):
https://docs.unity3d.com/ScriptReference/CursorLockMode.html
got it, thanks!
or yes intellisense
it was CursorLockMode.none
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?
That thing at top says "T must be a type that derived from InventoryItem"
but it doesn't say which derived class it is
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
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Let's say this was an ItemSlot<SomeOtherKindOfItem>
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);
}```
check #archived-code-general please
So even if I create a new object that derives from what I declared above, it doesnât know it actually derives from that class?
it knows it derives from that class
it doesn't know that it's the same derived class that was chosen as T
Ah, I see
It's not smart enough to infer that from your if (thing is Type) code
it could be but it isn't.
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
This should do it, but is ugly
why when i dash into the spike i cant move again ?
I can manage ugly for the time being, just want to get it working
presumably a bug in your code. Share it?
Once Iâve finished this project Iâll just start the next one and try to avoid the same mistakes
alr
https://codeshare.io/deO9KM this is the movement script
how do i make the particle that arl created not moving along with the object?
Well this is no longer throwing any errors, which is good. Will have to test it at runtime though
If you're using a Particle System component, you need to switch its simulation space from "Local" to "World".
you'll find this at the top of the particle system's inspector
nice got it
and this is the player death script when he collide with the spike https://codeshare.io/3yDJOv
I don't seem to see where you set isDashing to true or false
My guess is isDashing is never being set back to false
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.
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
How do I make a walkie-talkie using Photon Voice?
Pretty sure that's just what the class name looks like for a generic type (with 2 type params)
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
ah
actually, i'm more than mildly surprised. Can you show us the relevant code?
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
Show us the code.
https://hastebin.com/share/usumezicac.cpp Then if I try to create it,
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have a feeling that maybe scriptable objects don't work with this?
they will but with generic types it becomes complicated
you need to make your own editor tooloing to actually make instances of them
oh goodness
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
blast
But you can serialize them, at least?
yes
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
so in this case, would it just be better to simply avoid using scriptable objects and just make the inventories as is?
Let me rephrase - I think so
I think SOs are a good idea but not an SO with generic type params
gotcha
I don't really understand what this class is supposed to do. It's parameterized with a specific kind of inventory item and a specific kind of item
SOs have worked quite well for me so far
you've got yourself tied in a frustrating knot here unfortunately
Well it's supposed to be an inventory that holds one specific type of item, the slot holds that item and the item is defined there for methods that need it
Tell me about it...
Been struggling for nearly a month on this
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
To avoid me repeating the same inventory script three times
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
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
If you're already going to have distinct classes for each kind of inventory controller, I think it's reasonable to just do this
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
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?
Why is InventoryUniqueItem a whole separate class instead of just having a bool isUnique on the item class?
because a unique item is a completely separate class, not just a label for a base item class
this is a common problem in inventory systems
bear with me
What does it mean that the SpriteRenderer "isn't working"? What is it not doing?
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
iskeywords everywhere.
when i stop moving the sprite isnt what i set it to be
What is it actually and what should it be?
its like i m moving up and when i stop i want it to look up isnted of going to the default sprite which looks down
What does the animator do?
is the animator also setting the sprite?
yes
well there's your problem
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;
}
}
also 4 different bools is crazy
else if(right)
{
sr.sprite = s_left;
}```
đ€ đ€ đ€ đ€ đ€
yea its cuz its left but rotated 180
can u suggest a better method?
dictionary<direction,sprite> @sonic dome
enum Direction {
Up, Left, Right, Down
}```
oooooo
what does that do?
oh the key and value thing?
A dictionary lets you store a key with a value.
sr.sprite = spritesDictionary[direction]
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
I just don't know how I can physically do it that first way given how different the items are
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?
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
What are you trying to achieve with this code?
That the object moves into the direction the player looks
When he looks rigth, the object should be on his rigth side
why not just do player.position + player.forward, then?
that would position the object one meter in front of the player
Vector3 relativePosition = new(0, 0, 1);
MoveObject.transform.position = player.TransformPoint(relativePosition);```
@stoic glen
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
can anyone explain
with snapping and y = 0:
Vector3 localPos = new(0, 0, 1);
Vector3 worldPos = player.TransformPoint(relativePosition);
worldPos.y = 0;
Vector3Int rounded = worldPos;
MoveObject.transform.position = rounded;```
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?
well, what's the error?
hover over the errors and read them
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
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
No, you'll show the entire script.
If you knew what was relevant, you'd know how to solve the problem. Don't try to "prune down" your code.
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;
}
you'll read the bot message...
!code
đ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
đ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You put a semicolon where it doesn't belong.
Your screenshot did not include the trailing ;.
StatBoost = new Dictionary<Stat, int>();```
which was very important
It was almost deliberately cropped out
Very precise, yes.
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?
You can still serialize the fields
Then, for each enemy prefab, you can assign references.
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;
}```
You could just call AudioSource.PlayClipAtPoint in the Death function
Presumably your issue is that if the enemy dies, it's destroyed, which means the audio stops. This function will spin up a temporary object to play the sound and then destroy it when the sound is done:
https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
Or have a singleton sound-effect-manager. That's handy for preventing 50 copies of a sound from playing simultaneously.
What is not working? I don't see your initial question so it's probably a good idea to share that instead of asking a single person
which will explode your players' ears
you don't want to do pl.isDashing = true; when respawning...
Shouldn't that be false?
(and make the audio crap out)
I found the best cure for this is audiomixer + the normalize effect/filter or whatever đ
if my game is 2d, do i just put 0,0,0 for the position?
The position of what?
You pass in the position you want the sound to play at
It's not going to play the sound globally, just at the position
ah
2D audio doesn't get panned, does it?
I guess I'll just play it on my players position so it sounds global
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
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?
the sound of gaining points would not be positioned in the world
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
How do I make a walkie-talkie using Photon Voice?
Are the update() methods on GOs called in sequence on a single thread or are they called in parallel?
undefined order, non-parallel
Is there a way to get them called in parallel?
Not while still using ordinary Update methods
You could convert the whole project over to DOTS
which is also still not parallel but closer to it
I guess ECS and DOTS to the rescue.
Entities doesnât call update on gameobjects
thank u
I meant moving computation from update() into other functions that can get called in parallel.
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)
There's a whole spectrum of possibilities between "one raycast" and "infinite raycasts to every point on the target". You need to make a compromise at some point between the two.
The tradeoff is realism vs complexity and performance.
Raycast is smol
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)
1 raycast smol.
infinite raycasts beeg
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.
the position you see in the inspector is relative to the object's parent
You should not at all be worrying about performance when making references, especially at this stage
performance is a whole different beast.. and usually a later step in development..
if needed at all
Oh thx
yup, I wrote a little helper component that displays world transform
Is there a away to create something like folders, that it's more organisted
in what context?
That I can store the main elements like the player, camera, ligth and terrain in one folder, but the position isn't effected
in what context?
The project window?
The Heirarchy of the scene?
The hirachy
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
I'm just sorta figuring if I am aware earlier in development of whatever I am making it saves time and pain in the long run although I figure a variable ref is very unlikely to be performance heavy
make an empty gameobject
-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
Oh perfect thx
i usually dont nest my player tho.
nah references should not be the performance improvement you are looking for, should worry more about making the code clear and legible.
its usually more for props, lighting, effects, etc
yea, don't even worry about performance until u notice you need it..
so stuff that doesn't move
odds are you wont.. unless ur code is just nasty af
you get more performance hit with high poly models đ„Č
usually yes, but if they are at 0,0,0 even things that do move work out.. bc ur local positions are gonna be the same as ur global positions
but a player i usually keep root level just to avoid any issues that may appear
That makes sense
đ
ahh ofc, i only work in low-poly
funny b/c i am artist -> game-dev
but game-dev made me rethink using high detail graphics everywhere..
me decimating all my models
mortal poly count
as an asset user and a creator it sucks trying to keep things uniform
had a mesh the other day, 700K tris đ”âđ«
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
I use the same material on decimated mesh it looks just as good for my usecase
I usually make ps1-style game now anyway
thats more than my entire project.. and i mean my heavy project
like mspaint pallate ;D
less advanced materials == less lighting work i have to do
yeaaaaa thats the shite i like
me too but i havent been able to do it yet
need a good shader first
one with vertex wobble lol
yeah the closest i found finally works on URP
đ„ł
URP shaders are hard to comeby sometimes
im still hunting a good Outline shader
that isn't SS
not sure ur artsy level.. but found something that may be useful to u
when i start up unity i keep getting this error code. tried reinstalling and updating all my drivers. Assertion failed on expression: 'SUCCEEDED(hr)'
ayeee!
oh my shader im using might be the same
figured he'd just give some general tips
Im using this shader btw
https://assetstore.unity.com/packages/vfx/shaders/psx-shader-kit-183591
Successfully Failed đ
How do I make a walkie-talkie using Photon Voice?
lmao thats what i thought!
theres no more to that error @flint falcon
? can u show screenshot of console
@flint falcon update ur drivers
yup hold on
yeah I tried that
does the error actually break anything
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
it didnt the last 3 times i started unity
this time it freaked out shut off monitors and i got this
Oh yeah issue with your GPU
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
either gpu drivers are crashing somehow or yeah you might be pushing it to its apparent limits
its brand new 4070 super
make sure drivers are up to date
yeah just updated them
the nvidia ones not the microsoft ones
yup same
so geforce is happy?
have you tested other games / 3d applications
where might do that? in unity or in launcher?
device manager
ok now it will start but still the error for Assertion failed on expression: 'SUCCEEDED(hr)'
that error seems to have many different solutions
WTF are all these?
errors
Warnings
why?
they're called warning
woah ill take my lit tle succsesful error
yeh but what kind of errors?
There are too many Package Manager dependencies to list, stopping after 100
not sure what that means
lol.. try restarting.. /rebuilding the Library folder
how do I check which graphics card im using?
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
google and download "speccy" to run a quick diagnostics on your computer
of the specs
CPU-X
Task Manager
speccy n ccleaner are spyware
i ment in unity
Why would you mean that?
so is discord ( hot take )
i use cccleaner all the time đŹ
Spyware doesn't mean "software I don't like" it has an actual meaning
no idea im grasping to get this guy working right lol
chinese CCP watchin u
False take
u have tiktok?
nope
Well, don't check it in unity
i know which one i have
alternative?
its new
i just maintenance my OS myself lol
It's not malware. It's just a horrible program and generally has more chance to brick your OS than actually "clean" it.
My secondary monitor was plugged into directly the motherboard. Pluging it into my videocard instead solved the issue.
@flint falcon alternatively you can try HWInfo
for the most part windows knows how to take care of itself, I just use something like spacesniffer to delete the TEMP garbage
theres 100s of solution for that error nicky..
lol greaty
not sure which one fits u
most of those "OS cleaners " are spamm
c an i just leave it there?
And completely pointless too
agreed
you're coding games!
đ€«
no way registry is harder
i'll give it a shot
type regedit and ur golden
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
"im gonna makeup some "issues" so you keep me as useful tool " 
hahahah.. i mean could be fax..
it does show keys i remember deleting already lol
give us something good CR7
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)
aww, disappointed
showing wrong script bud
whats on line 28 of SelectionManager.cs?
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
Either interaction_text or selectionTransform is null, or selectionTransform does not have an InteractableObject component on it.
Consider logs to find out which one it is
oh there is a link :
lol me too
Yeah the link is to SelectionManager and the image is InteractableObject