#💻┃code-beginner
1 messages · Page 66 of 1
youre supposed to put the white cursor on it and read the values on that frame
expand the arrows untill you see the cause of high ms/gc alloc
okay
EditorLoop is the unity editor
i think i got it what is happening like if i select a cube(Spline Animate) while playing in editor it drop downs to 180 -200 but when i select something like fog it goes back to 600-800
is it because its debuging the value in inspector?
what I would do to be sure is run a standalone profile
you would be able to see if the editor is just causing too much overhead
sounds like the inspector for the spline being slow, but again, you;'d have to profile to know for sure
aight will surely look into it
Yeah, inspectors can be very slow.
especially if they're all IMGUI-based and you have a gigantic pile of complex components
as I've experienced recently
esp when you have lots of gizmos xD
the more inspector has to draw the more ms you lose thats why its best to test in maximized game view, with release mode enabled
yes with gizmos disabled
ideally test in build
but release mode maximized is pretty close
not sure if it's been mentioned yet: remove all Debug.Log command before profiling- these can get SUPER slow.
right because those get sent to editor console which also hogs like crazy under spam
what should i look at if i want to like have spells like in original Dragon Warrior? How to store how the magic and what it does?
like Heal, Heal All, Magic Blast thingy
never heard about that game, but common place to start is ScriptableObjects and Prefabs
A strong arm and quick thinking alone are not enough to achieve your goal of freeing Alefgard. Since the beginning of time, Magic has been a force in this land, shaping its history and the beings who dwell here. As you gain experience and reach particular levels and achievement, you will learn new spells that will help you succeed in your perilo...
now i miss it
yea, im thinking about SO approach but that would like need me to make many .cs files, for each spell
im quite allergic to making many files, idk why
why would you need many files with SO ?
teehee, I dig that username! Not sure how thy do it in the game, but I'd suggest some kind of heiarchical structure- base class to store stuff common to all spells (mana cost, min level to cast, etc...) and derived class to implement each spell, which will probabably require an overriden function for "Cast" or "Effect"
this the reason it have to be many file
yeah but You only create 1 script for each no?
but can create many SO from 1 file
if you make em SO's, then I'm afraid so- unity requiriment
not necessary
second approach im thinking is a SpellLibrary and reflection, but is quite nasty
you can have a single SO representing a generic spell, and in that SO you reference a type of spell behavior it will use
and dump all your spells in a massive .cs each as a separate class
or serialize an instance of those classes right in the SO with Odin, for example
that too, then switch?
i had a custom unityevent approach before, but it was painful to set up
you dont have Odin?
public void Satiety(Creature toHeal, int potency, Vector3 targetPos, Matter Target)
{
var activeSat = toHeal.GetComponent<Satiated>();
var eaten = InventoryManager.LastItemUsed;
if(!activeSat || activeSat.Duration * activeSat.Intensity < eaten.ItemData[0] * eaten.ItemData[1])
{
toHeal.gameObject.AddComponent<Satiated>().Inflict(eaten.ItemData[0], eaten.ItemData[1]);
}
}``` this will be registered to unityevent, but is so annoying if these parameters dont have what the spell need
no odin
you can use type reference but then no per instance parameters
type reference?
hmm.. ig imma just go with simple, partial class holding an enum switch
yes you can relatively simply serialize types
https://github.com/pointcache/unity3d-safeTypeSerialization
ancient repo but the principle works
nothing's ancient
same thing microsoft is doing in its libraries with TypeID attribute
hi guys
Android resource linking failed
C:\Users\flyup.gradle\caches\transforms-2\files-2.1\ed3a49a6baab5d780d3e657791554ea9\com.google.android.gms.play-services-measurement-api-21.5.0\AndroidManifest.xml:30:9-32:61: AAPT: error: unexpected element <property> found in <manifest><application>.
does anybody familiar with this error
attach guid to any type with attribute, serialize that guid, and you will never lose a reference to that type
is this repo like SerializeReference?
it is specifically a serialized Type
lemme try the demo
try asking in #📱┃mobile, better chances in there
I think it's incompatible in my unity
who can help me with a certain issue
Just ask your question, there are 20000 people online
follow me privately
No
come onnn its argent
if its urgent you would spit the out the question instead
not sure what can be incompatible, maybe it was made in 2018 and serialization fails
what is that file?
your SO instance
just create new one
interesting
if I use this SO, it automatically makes a new instance of the Ammofreezing?
i dont know what it does
u wrote it
the reference just will return you the type
use Activator.CreateInstance(referencedType)
this can be accessed with ```cs
SO.ClassToSpawn.AmmoFreezing();
hunh? A System.Type IS an object
so this SO kinda need a supporting field that accepts an Ammo object?
yes but its an object of type Type not of the end type that has method AmmoFreezing
yes
Guess it wasn't that argent
this is the selling part, I see
var
class HealSpell : SpellBehavior
{
public override void OnSpellCast() {
// do healing
}
}
class SpellSO : ScriptableObject
{
public SerializedType spellType;
public Spell GetNewBehaviorInstance() => Activator.CreateInstance(spellType);
}
class Spell
{
private SpellBehavior _behavior;
public Spell(SpellSO so)
{
this._behavior = so.GetNewBehaviorInstance();
}
public void Cast()
{
_behavior.OnSpellCast();
}
}
Sorry being silly: I avoid ''var'' like the plague. never clear what it is.
this is cleaner than switch at least and cool, lemme try if i can like do it
in my experience, it goes away after some rounds with stuff like
IReadOnlyDictionary<Dictionary<ICollection, HashSet<Vector4>>> dict = new IReadOnlyDictionary<Dictionary<ICollection, HashSet<Vector4>>>();
after a while it just stops being an issue
yeah totally var that
[ExposeType("deliberateGibberishHereCanBeUsedOrStandardGUIDGenerator")]``` it doesnt matter what's in here right?
hard disagree
no just that its unique
and never changes
if you want one that doesn't use attributes, https://github.com/glurth/SerializableType this one uses the AssemblyQualifiedName. (The editor I made for it sux, but works)
Contribute to glurth/SerializableType development by creating an account on GitHub.
assembly qualified name will suffer from all the issues any other type of serialization except attribute suffers
Reminds me that I need to change some data structs to IReadOnly for my immutable SOs
oh! tel me more!
what kinda issues?
oh! yah, totally
[assembly: BindTypeNameToType("MyOldNamespace.MyNewTypeName", typeof(MyNewNamesSpace.MyNewTypeName))]
you will still need to use attributes when you will be renaming types
"Odin's variant was added to support the rare (and not recommended!) case of property serialization."
teehee
yes, rare
Odin is half off right now and debating on grabbing it, but the licensing doesn't seem game jam friendly or unless I'm misunderstanding something.
cant it work with this set up? Every class need it's own attribute?
yes every type needs its own
AND they must be unique
you can just use any Guid generator
like immidiate window in VS
or Insert Guid extension
tbh that lib needs to be refactored to actually use Guid and not strings
my defence is im showing an example of an approach to solving the problem
one of many
most reliable id generator
@sharp wyvern No reaction gifs, please
fun
i have made a gun script for my gun that adds recoil to the gun (the gun shakes, but the camera doesnt), and i have a seperate script for using the camera in my fps game (naturally)
i wanted to implement when i fire my camera jerks
and i was wondering whether i would put this "camera jerking" code into the gun script or into the camera script
Why isnt this working? '''if (isCrouched && ControllerinUse && ((Input.GetAxis("Horizontal") != Mathf.Clamp(Input.GetAxis("Horizontal"), -0.1f, 0.1f)))) { isCrouchWalking = true; } else { isCrouchWalking = false; }
I'm trying to check if a float is NOT within two numbers.
well that's certainly not how you check if a number is within a range.
I fixed my issue, but how should i do it?
check if it is greater than the max or less than the min to determine if it is outside that range. don't clamp it then check equality. especially with floats where you shouldn't be checking direct equality anyway
I would probably put it on the gun. If you put it on the camera than you have to call it from the gun, which means the gun script would no longer work if you transfer it into another project without the camera script.
I guess you could also have an event on the gun that gets invoked when the player shoots, but that feels a little overkill
Hey guys i have 1 prefab for my boss and use instantiate to summon it.. every 1m appear the same boss.. but if u cant kill it will appear again another one in 1 min.. but the prob is some how the second one or both are sometimes sharing or taking damage for the other.. what could it be? Done the same with other enemies and all good.. and its just a prefab being instantiated.. should instantiate it as dif objects and dif hp etc no?
alright, thank you very much
What's different about your implementation of your normal enemies and bosses?
nothing all the same.. i have a prefab that I use instantiate toi spawn them in dif times or situations
maybe you are reducing the health from the prefab instead of the clone when they take damage
we'd have to see how the damage is applied . . .
private BossOne _boss;
//on start
_boss = FindObjectOfType<BossOne>();
/onTriggerEvent
if (other.tag == "BossOne"){
_boss._bossOnecurrentHealth -= _playerBulletDamage;
SpawnTextAboveHead(_playerBulletDamage);
Destroy(this.gameObject);
}```
Should bind your boss references via inspector instead of finding it through FindObject. Rather, bind the prefab instance then on each instantiation place those new boss references somewhere you can indentify apart from.
FindObjectOfType() could get either of the bosses and not the one that is going to be hit, right? Why not get the boss from the 'other' object:
other.GetComponent<BossOne>();
then you know it's the one that got actually hit.
Find will select the first one it finds in the scene. if there are more than one, you have no idea which is selected . . .
hmm ok thank you !! will try
But you shouldn't care if you hit the boss or a normal enemy. I assume both just lose health right?
You can make use of an interface:
//Create a new script that only contains this
public interface IHitable
{
public void TakeDamage(int amount);
}
-----------
public class BossOne : MonoBehaviour, IHitable
{
...
public void TakeDamage(int amount)
{
health -= amount;
}
...
}
private void YourColliderMethod(Collider other)
{
hitable = other.GetComponent<IHitable>();
if (hitable != null)
{
hitable.TakeDamage(_playerBulletDamage);
}
}
Then you implement the interface for your normal enemies as well and now your bullet doesn't care about what it hits, as long as it has the IHitable interface it will call the TakeDamage() function from that script.
I highly recommend you try and learn this, if you improve your C# skills you will eventually write the code you are currently writing but in 1/10th of the time.
This is not a proper way to get an interface component, you need to either cast it to Unity Object or use TryGetComponent() instead. You may read more here
what? that code is completely fine
No
Yes
its completely fine, they just have an extra step. it's not necessary but TryGetComponent will do both in one go, yes . . .
But it is true that this will not test if you've got a reference to a valid unity object.
iirc GetComponent returns an object reference if it fails to find something
It's not completely fine, it will fail if object is destroyed
correct idea, just worded weirdly :p
so yeah, you're right: the code is not correct
TryGetComponent is the way to go here.
Thanks. I'm a programmer, I don't speak human language very well
but I'm glad you got what I meant
I wish there was some kind of way to make a type shaped like
"Any Unity object that implements X"
That isn't possible with C#'s type system
It would vastly improve how you deal with components that implement interface types
well it fixed the prob but now I have another one that in this code ```cs
private void OnTriggerEnter2D(Collider2D other) {
BossOne boss = other.GetComponent<BossOne>();
if(other.tag == "Enemy") {
Destroy(this.gameObject);
}
if (other.tag == "BossOne"){
boss._bossOnecurrentHealth -= _playerBulletDamage;
SpawnTextAboveHead(_playerBulletDamage);
Destroy(this.gameObject);
}
if(other.tag == "BossOneMinions"){
boss._bossOnecurrentHealth -= _playerBulletDamage / 2;
SpawnTextAboveHead(_playerBulletDamage / 2);
Destroy(this.gameObject);
}
} ``` the BossOneMinions was working and before was like _boss_bossOnecurrentHealth -= _playerBulletDamage / 2; and finding the boss witht he find method. the boss minions now gives me object reference not set to an instance in the line ```cs
boss._bossOnecurrentHealth -= _playerBulletDamage / 2;```
but in the line cs boss._bossOnecurrentHealth -= _playerBulletDamage; all good
because they don't have a BossOne component attached. I recommend you add a reference to the boss in the minion script. When the 'other' object is a minion you get the Minion script and call a method that then will redirect the damage to the boss. I also recommend you read what I wrote above.
ok thank you very much.
i have a bit of code attached to an object with a 2d box collider and it is a trigger but none of this code is being run on star any ideas why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractableObject : MonoBehaviour
{
void Start()
{
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null)
{
Debug.LogWarning("Player found");
}
else
{
Debug.LogWarning("Player not found. Make sure to tag your player GameObject with 'Player'.");
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Debug.LogWarning("YAYAAYAYAYAYA");
}
else
{
Debug.LogWarning("Collision with non-player object. Tag: " + collision.tag);
}
}
}
Post a screenshot of the script in the Inspector. It might be disabled
whatcha colliding with
the player object with the tag "Player"
Select the script in your assets (your project files). Its contents will appear in the Inspector, make sure it's identical to what you're seeing in your code editor
you have 3 LogWarnings there but you have hidden them
Does anyone mind helping me with some script code? I'm following a tutorial for a simple inventory system. I have it working that the object gets clicked and destroyed and saved into an array for the inventory but the UI is not updating with the sprite image and name. I'm not really sure how to fix this and would really appreciate if someone would take a peek at this
post codes
Hey, guys! If I don't want to destroy a gameobject on all of my scenes but only for one specific scene is there a way to do that? I mean can I get maybe a reference to my MainScene for example and make it?
If it exists between all scenes (DDOL) then deleting it will delete that specific instance. Why not just hide it if you don't want to use it on that specific scene?
`public class InventoryManager : MonoBehaviour
{
public static InventoryManager Instance;
public List <Item> items = new List<Item>();
public Transform ItemContent;
public GameObject InventoryItem;
private void Awake()
{
Instance = this;
}
public void Add(Item item)
{
items.Add(item);
}
public void Remove(Item item)
{
items.Remove(item);
}
public void ListItems()
{
//clean content before you open
/* foreach (Transform item in ItemContent)
{
Destroy(item.gameObject);
}*/
foreach (var item in items)
{
GameObject obj = Instantiate(InventoryItem, ItemContent);
var itemName = obj.transform.Find("ItemName").GetComponent<Text>();
var itemIcon = obj.transform.Find("ItemIcon").GetComponent<Image>();
itemName.text = item.name;
itemIcon.sprite = item.icon;
}
}
}` I'm pretty sure this is where my error is gonna be. The part I commented was something I was trying
```cs
//Your code here
```
Looks like you modify the list while iterating it?
Oh, ItemContent is a transform, so you're destroying children? (Lol)
Oh? Do you mind if I dm you so I can ask more questions and not spam the chat. If not I can send my questions here
jesus christ, that code is from a tutorial? Mind sending me a link?
Best to just ask here, many people more experienced than me are here. If you want, you can make a thread.
best help will be here where multiple people can have eyes on it . . .
Destroying, instantiating, then using find on that same exact GO is quality
Inventory system is used in most of the games. If you need an inventory system in your game, this video is for you. In this video, I will teach you how to make an inventory system from scratch. Enjoy watching.
❤️Support me on Patreon: https://www.patreon.com/solo_gamedev
💙Subscribe to My Channel: http://www.youtube.com/c/SoloGameDev?sub_confirm...
Does your InventoryItem have two children with the names "ItemName" and "ItemIcon" with the same capitalisation?
I’ve only made it about halfway through the video because when I stop to test something is always broken
trying to call this script i made to show a dialogue system
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractableObject : MonoBehaviour
{
public DialogueTrigger dialogueTrigger;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
try
{
dialogueTrigger.TriggerDialogue();
}
catch
{
Debug.LogError("DialogueTrigger component not found on the player GameObject. Make sure the DialogueTrigger script is attached.");
}
}
}
}
But when ever its called it says object not found
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogueTrigger : MonoBehaviour
{
public Dialogue dialogue;
public void TriggerDialogue ()
{
FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
}
}
i have made public class and dragged the script into it so i dont know why it doesnt work
public class Item : ScriptableObject
{
public int id;
public string itemName;
public int value;
public Sprite icon;
}``` This is what I have for the items which is why I think I had to make the var in the ListItems() method
It is based on gameobject children. Do you have children on the gameobject?
Hide it like how? How to hide that instance? I have tried to make GameObject musicGameObject; and after that set that object active to false but that doesn't do what I want, so I want to destroy on load for my main game scene not for every scene. Because I made a dontdestroyonload script and I am not destroying the gameobject of main menu music to my options scene as well but for one reason it still continue playing on my other scenes when loading those scenes.
Do you have a DialogueManager active in the Scene?
Maybe getting a null exception from using Find then trying to access the null
Hello guys,
Scarpis here, thank you for helping me!
Unity version: 2022.3.9f1
Please help me fix the error, i want to be able to use PRIVATE GameObject name instead of public
I want to reference a game object into a PRIVATE variable and i am getting the following error:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:22)
Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
private Rigidbody playerRb;
private GameObject focalPoint;
// Start is called before the first frame update
void Start()
{
focalPoint = GameObject.Find("Focal Point");
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
// playerRb.AddForce(Vector3.forward * verticalInput * speed); we need to rotate with the camera focal point, see below
playerRb.AddForce(focalPoint.transform.forward * verticalInput * speed);
if ( focalPoint == null)
{
Debug.Log("NO REFERENCIA");
}
}
}
please format the !code or use the suggested links to post your 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.
this is what I have for the inventory slots (there are more Item's but its a lot so I'm showing the first one)
show us the hierarchy of the "Item" GameObject . . .
how would one do that
the error tells you why it's not working. You need to add a DialogueTrigger to your player gameObject
why?
var itemIcon = obj.transform.Find("ItemIcon").GetComponent<Image>();
this line looks for a child GameObject named ItemIcon. you do not have a child with that name in this pic . . .
Hello guys,
Scarpis here, thank you for helping me!
Unity version: 2022.3.9f1
Please help me fix the error, i want to be able to use PRIVATE GameObject name instead of public
I want to reference a game object into a PRIVATE variable and i am getting the following error:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:22)
Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
private Rigidbody playerRb;
private GameObject focalPoint;
// Start is called before the first frame update
void Start()
{
focalPoint = GameObject.Find("Focal Point");
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
// playerRb.AddForce(Vector3.forward * verticalInput * speed); we need to rotate with the camera focal point, see below
playerRb.AddForce(focalPoint.transform.forward * verticalInput * speed);
if ( focalPoint == null)
{
Debug.Log("NO REFERENCIA");
}
}
}
Thank you!!!!
are you copying the code from your IDE bcuz it's not formatted at all. which line is 22?
im sorry, just did!
Why? Why what?
I don't know too much about Unity's audio modules, but I'd assume if you're disabling the exact game object with the audio script then it should be prevented from playing so double check on that. Perhaps you need to terminate the current clip from playing before disabling.
This is the 22 line
playerRb.AddForce(focalPoint.transform.forward * verticalInput * speed);
Stupid end of the day, very tired, simple maths question incoming. lol.
How can I take a range of 0 - 1.71 and normalise it between 0 - 1 ?
I changed the "ItemIcon" to "Image" because that's what it's called but the UI is still not updating. But thankfully the inventory manager game object I have still shows that the item is in the inventory array
thanks for your help... i cannot understand why i cannot use the private GameObject focalPoint
divide by 1.71
Thank you.
looks like focalPoint is null. you attempt to assign it in Start. when using Find, make sure the name is spelled correctly. is the GameObject named "Focal Point" and does it exist in the scene when the script runs?
🤦♂️
i dont understand why i would need to add the Diaulogue trigger to the player object could u try explaining cause i am really confused
If you change the name, you need to change the code
I did not change the name of the object, I just changed the code to match the name of the object
not sure why you changed the name because the code is looking for the GameObject name "ItemIcon", not "Image" . . .
That error is generated from your code, or the code you got from somewhere. Double click the error and it should show you the line where the error is getting send from. I don't know the code so I don't know why
Yes, there is an object called Focal Point. do you think its not finding it because of the space between Focal and Point?
just relised that was a testing thing from what i was doing earlier
Debug.LogError("DialogueTrigger component not found on the player GameObject. Make sure the DialogueTrigger script is attached.");```
should i just run it without the try and see the error?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractableObject : MonoBehaviour
{
public DialogueTrigger dialogueTrigger;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
try
{
dialogueTrigger.TriggerDialogue();
}
catch
{
Debug.LogError("DialogueTrigger component not found on the player GameObject. Make sure the DialogueTrigger script is attached.");
}
}
}
}
@cosmic dagger
ok i now know how to fix it thanks 🙂
I wouldn't use try-catch statements there since they hide the real error. I assume dialogueTrigger is not assigned in the Inspector for your InteractableObject
Oof yeah, I'd just use a Debug.Assert() in Awake or Start for that
Debug.Assert(thing != null, "your error message here")
it was and issue with the dialogue manager i fogor to define something
but thanks for the advice ill do that next time
any clue and how to fix the reference error?
By giving it a reference and making sure it's not null
have you even tested what is actually null yet?
i dont want to use
public GameObject name
i want to be able to use a private reference
Yes, i have a debug.log that is showing that focalPoint is null but in start() i did initiate it
on the line you indicated playerRB or focalpoint could be null. check it
Hey, guys! If I want to get reference for a specific scene in my game how to do that?
Why are the objectHitRenderers are null?? Everything seems perfect, and when I debug the meshRendererArray it shows all of the renderers
to do what with?
I dont know can I do that btw?
thanks for the help. i did test the playerRb and its working... i think is not able to find the Focal Point game object in the scene
public SceneAsset myScene;
I mean not an asset a unity scene?
When I am making a scene in my game that scene
Try it
Check the game object name, make sure there is no space at the end
or add a script to the gameObject and look for that
Alright!
Also make sure Focal Point is not being deactivated
I updated the name of it but it is still not working. And I also realized that I'm having a separate issue with the inventory where if you close it, all the slots disappear and if you click an item only one slot comes back but it doesnt update and it pauses the game. I'm getting this error but I'm not sure what is null and I noticed it's no longer reading the name of the object (it did this previously)
oops I responded to the wrong message
OMG bro! u are the best.... i was looking everywhere, even in the entire unity forum... the space at the end of the "Focal Point "
Solved!!! it was a space at the end of the game object name...
@languid spire im glad i found you here, i wasted about 3 hours of my learning today just because of this !!! Thank you again and im sorry, im still a newbbi
Gotta think like Sherlock Holmes
I hope the lesson you learned is not to look for things by using strings
Whenever you call ListItems() you are effectively destroying all gameobjects and creating a whole new set of them, then goes through each new GO to grab the children GOs (text and display). By all means, it probably isn't that big of a deal, but really you should be updating the inventory per itemslot modified.
Do you mind helping me write those changes? This is my first time working with Unity and C# so I've been relying on tutorials and have been struggling trying to write the code on my own
Right, so first you need to think about the requirements. Are you having a specific set of inventory slots, or can you modify it later in the game to have more capacity?
Anyone could help?
im not that advance yet.. as soon as i find a better way i will use it
I have a set amount (25)
Thanks again Steve!
So because you know the exact amount, you can just populate the amount of slots on the UI and never touch the composition again. You can even use an array if you want over a list since you know the exact capacity of it all.
Finally got pooling working!
I have all 25 in the UI already. And I commented out the destroy(gameobject) in my ListItems() method which fixed my problem of the slots disappearing when I close and re-open my inventory. When I click the items they save in the inventory, but the UI never updates
What do your slot prefabs look like?
So, personally instead of using find I would make a script for your slots which have the direct reference to the children
this would cut down the Find() shenanigan's you're doing when you update your inventory
Then with these new scripts you can have your inventory grab these slots by their component (their new slot script) instead of directly using the GameObject reference.
This is the second inventory system i'm trying to use and the other one had a slotUI script, would the one your suggesting I make look something kind of like this?
Right, instead of letting the inventory know everything, you break it down so the slots contain their own set amount of data.
does this script go on the slots themselves?
Yeah, delcare a set of variables such as their icon and text
you can then directly set these variables on the prefab in the editor, or use OnValidate() and grab the children via GetComponentInChildren()
icon here can just be the type of Image instead of GameObject
and text would be type of Text or TMP_Text, whatever you're using
I'm trying to re-use the existing script to fit this situation
GetChild returns a Transform, not an Image component . . .
And Image does not have a SetActive method . . .
yes, i changed the type for icon and am now trying to update everything
You can just change the opacity of Image, otherwise you'd use enabled was it?
SetActive is a method of GameObject
The reason why you want to define your variables by the component and not the GameObject is to prevent binding incorrect types via editor
I am stuck trying to figure out what to change this to
What does the error say?
Is icon a transform?
GetComponentInChildren<Image>() ?
icon is of type Image
Well a child is a transform
Get the image from the transform, or do what Glurth said
this is what I have currently
icon = GetComponent not icon.GetComponent
then to access gameObject stuff like isActuive or SetActive use icon.gameobject.SetActive...
there is no need for the GetComponent inside RefreshItemIcons
you already got the component in Start
icon is already an Image
^ good point
I took that line out, thank you. This is a script from a different tutorial that I am trying to update and re-use
welll... not the line - you still want the icon assignment
Wasn't there an enabled method for images specifically or am I dreaming
this is the whole script
Hi!
good day.
i need guidance for my project.
i created a menu and i want when it get clicked on its buttons a costume made animation run.
i created the animations But i dont know how to summon it. do i need to use a bool for animator or an trigger?
i ll be thankfull if you tell me how to summon in code?
When it comes to adding and removing data, that's when you'd update the slot specifically. Your previous script was basically refreshing the whole inventory is the idea of doing it this way instead.
I’m sorry. I’m having a bit of difficulty keeping up and understanding
Whenever you insert your item data or remove your item data from a specific slot, you'd set the image and the text for that specific slot. Previously you were having to delete all gameobjects everytime you wanted to display the inventory.
Ahhh okay
So, now your inventory script should instead be grabbing all of these slots and putting them into a list or an array for it to navigate through.
public class Inventory : MonoBehaviour
{
private List<ItemSlot> slots = new();
public List<ItemSlot> Slots
{
get { return slots; }
private set { slots = value; }
}
public void Start()
{
ItemSlot[] itemSlots = GetComponentsInChildren<ItemSlot>();
foreach (ItemSlot itemSlot in itemSlots)
{
Slots.Add(itemSlot);
}
}
}```
Something like that
Hey, anyone can help me figure out how I can look around with the camera while also inheriting the rotation of a specific transform?
This is my script for looking around:
HeadModeRotationOffset.x += mouseX;
HeadModeRotationOffset.y += mouseY;
HeadModeRotationOffset.y = Mathf.Clamp(HeadModeRotationOffset.y, -90f, 90f);
Quaternion yQuaternion = Quaternion.AngleAxis(HeadModeRotationOffset.x, Vector3.up);
Quaternion xQuaternion = Quaternion.AngleAxis(HeadModeRotationOffset.y, -Vector3.right);
transform.rotation = yQuaternion * xQuaternion;
"targetPosition.rotation" is the head variable that I want to inherit its rotations (bobbing)
How's the camera in your hierarchy?
It's not parented by* anything
Item selectedItem = GetSelectedItem(false);
if (selectedItem != null)
{
if (itemHolder.childCount <= 0)
{
selectedItemModel = Instantiate(selectedItem.model, itemHolder);
IEquippable tool = selectedItemModel.GetComponent<IEquippable>();
tool.Equip(itemHolder);
}
}
else
{
Destroy(selectedItemModel);
}
```Anyone has any idea on how to make it work properly? (Whenever I hold 1 item and then switch to other, it doesn't change the viewmodel. To fix that I have to switch to empty slot and then switch to desired item)
You can't parent the camera under the transform you want?
I would rather avoid that. I'm trying to only inherit the head* bobbing in code
Assuming your tool.Equip method isn't throwing errors, then I don't see anything wrong with this code here. Probably explain it a little more if possible.
I do head bobbing by just moving the local position of the camera, specifically just the Y axis, that's parented under the Player game object. But that's for a first person game setup.
Yeah I don't want to make it parented by the game object. The only thing I'm getting out of chat gpt is to multiply the rotation of the head like this:
transform.rotation = targetPosition.rotation * (yQuaternion * xQuaternion);
But this messes up my controls and everything...it does however inherit the head rotations correctly
So I just want to inherit those head rotations without messing up my camera's looking around feature
How is that you want to do the head bobbing? Is it suppose to rotate more or less like in a call of duty game?
left and right
You can store the look around code in a variable and then apply the bobbing rotating by the end of the Update method
I've done this a couple times to apply stuff like head bobbing and camera lagging to kinda "force" the transform to assume a specific rotation or position
So you modify each variable independently and then apply them up at the end so each effect don't interfere with each other
this being a new script?
New being the purpose of the inventory script now. It'll manage the slots, but the slots now have their own individual instance of datas.
When you say apply the bobbing rotating, you mean manually add the rotation or actually inheriting the rotations?
If you want to check if a slot is unoccupied, you'd consult the inventory and it'll look through the slots and return an index to insert data into if available.
Manually add the rotation. You have code that controls how the camera looks around. Save that to a property and then at the end calculate the head bobbing, and then apply both the look around property and the head bobbing to your transform rotation.
what's the problem here? the first script is for the movement, the second is to disable the movement if there is a collision, and the third is to make obstacles not move at all if hitted
Sorry, I will explain tomorrow, it's too late rn
so now these are the scripts that I have
No One??????????
You enable and disable its own script. Never the movement script
The name of the variable is irrelevant. It's the type that matters
so i have to call the movement script, but how?
By making the type objectSpeed instead of ObstacleBehaviour or ObstacleCollision
Then drag in the script
I strongly recommend stopping and doing this
https://www.w3schools.com/cs/index.php
It's short and will help tremendously.
Then move on to this. It will help you specifically with unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the beginner pathway is not working
i am doing a tutorial
Do the c# course first anyway
Don't do youtube first
but i wanted to try to do something with what i know
Inventory, Slot, and however you're managing your item data (which should have a variable declared inside of each slot for them)
Well, I don't know if you are at the point for that. Making a reference is just about the first thing you should learn after what an int, string, etc are
But you can certainly make your own choices
sorry
i'll learn to learn
No need to be sorry. I don't mean this to be rude, i just want to see you succeed and not burn yourself out.
The course i recommended is short. You'll do great
ty
which is the c# course?
variable in the prefab? or somewhere in the script?
The w3schools one
Alright thanks
w3school is a website
oooh
they offer different courses for languages
freecodecamp has some good ones too
they released a C# certification course recently
i know a bit of c#, can i skip what i already know?
No. You need the very basics of c#, that is where you are struggling
At least learn what a type is
int, float, bool
that right?
Those are primitive types yeah
Now learn what non-primitives are
ok
every time you do public class < something > you are creating a new type
same with struct and enum
Just keep in mind that Unity is just a c# api. Knowing c# is the most important part. Then learning unity is much easier
ok ok ty
i'll learn it
i already coded a bit in python so i hope it will be easier lol
The biggest difference is gonna be typing. Python is dynamically typed while c# is statically typed.
There are 100 other differences, but that's the one python users seem to struggle with most in my experience
okk
see ya
how to make player move script?
!learn will provide multiple examples
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You gotta choose Character Collider, Kinematic/Dynamic Rigidbody, or Transform based movement
Best of luck!
im sorry can Anyone help me?
i created a menu and i want when it get clicked on its buttons a costume made animation run.
i created the animations But i dont know how to summon it. do i need to use a bool for animator or an trigger?
i ll be thankfull if you tell me how to summon it in the code?
yeah you can use a bool for it
for instance animator.SetBool("Run", true)
need to create a bool in the animator tab and transition it though
Has this happened to anyone else before? Project and assets all imported properly everything completely fine, but then you load your project and everything is blurry? Thank you!
so how do i relate it to button on menu?
You declare an item variable inside of the slot but you don't necessarily need to reference an item just then. So technically you iterate over your slots from your inventory and check each slot if it has set data or if the item variable is null. If it's null then that means it's empty and you can insert a new item reference into it.
you create a new public function and set the animator bool to true on that function
and drag it to the button
im making adding a recoil effect to the camera when i fire my gun where the camera "jerks" upwards on the OnGunShotEvent, however i have a problem where the camera keeps returning to its original position after it has jerked upwards and i have no clue why
like normal run animation?
Assets\Origami\Assets\Holograms\Support\Spatial Mapping\SpatialMapping.cs(27,13): error CS0246: The type or namespace name 'SpatialMappingCollider' could not be found (are you missing a using directive or an assembly reference?)
I am importing the hololense v1 tutorial and getting this error. What do I need to do to fix this
what do you mean
is there a script called SpatialMappingCollider?
yea
i mean for my run i made an float in animator and gave it a condition for walk and a made a bool for run saying if shift is held make it true.
I don't see one
i saw this on many toturials
then that's probably why
where's the script?
so what are you looking to do then?
when u click a button the run animation is set to true?
This is the project folder, we drag and dropped it to assets
in unity 2019 lts
it's the v1 hololense but it should have all the files
I'm wondering if it's our verson of xr plugin or something?
i did'nt know to use trigger or bool for it ? and i though because its menu button i should use a diffirent method.
thanks for guiding me.
well its the same thing as u did with clicking on left shift
why would they upload it with missing scripts on microsofts website?
Is there a way to prevent pixel art from doing that individual pixel slant thing when it is rotated?
are you missing some other package or something?
anti aliasing?
I don't think so, We have xr plugin installed
I wouldn't know enough about this package to say for certain
see if anybody else has had this issue online maybe
anti aliasing is not affecting anything
can I see your sprite
and show it how it looks when slanted?
y'see how it has that weird slant on the pixels? Do you know how to fix that?
those looks bumpy, not pixelated
can I see your sprite's settings?
try setting compression to none
doesn't do anything
looks the exact same?
yeah no changes
I might check #🔎┃find-a-channel since this channel is meant for code, there might be some more experienced people with sprites there
would this work?
this will work for the first null item only
are you running it multiple times?
Looks fine for the most part
im making adding a recoil effect to the camera when i fire my gun where the camera "jerks" upwards on the OnGunShotEvent, however i have a problem where the camera keeps returning to its original position after it has jerked upwards and i have no clue why
https://hatebin.com/rwmnmsogpy
i just want it to jerk upwards, forcing the player to pull the mouse down to combat the recoil
Do I attach the Inventory.cs script to an empty object that acts as a handler? Or to the inventory prefab objects themselves?
Yeah, it would be in the scene. It be the parent of all the slots.
sorry if this is the wrong chat i could not see anywhere to put it. So i use this ````else if (addTicketsCommands.enabled && addTicketsCommands.commands.Contains(command))
{
if (!addTicketsCommands.adminOnly || IsAdmin(username) || (addTicketsCommands.streamerAllowed && (username == TwitchChat.Instance.channelName || username == TwitchChat.Instance.nickName)))
{
if (addTicketsCommands.ticketCost == 0 || UseTickets(addTicketsCommands.ticketCost, username))
{
try
{
onlineDatabase.Instance.addTickets(message.Split(' ')[commandIndex + 1].Replace("@", ""), int.Parse(message.Split(' ')[2]));
TwitchChat.Instance.SendChatMessage("@" + username + ", added " + message.Split(' ')[2] + " tickets to @" + message.Split(' ')[commandIndex + 1].Replace("@", "") + "'s accounts.");
}
catch
{
TwitchChat.Instance.SendChatMessage("@" + username + ", Could not add tickets to player.");
}
}
}
}``` which is a admin command to add tickets to someones account by doing !addtickets @(username) x-amount but when i try and set it so any one can use the !addtickets 300 i cant seem to get it to pick up the person that used the command or add the tickets and anyone help
this channel is for Unity concepts
I'm sure there's a discord.js discord server, or something similar, I would ask there
its a unity scipt not a discord script
ah, my bad
your command looked like a discord command
you're good then
the script sets up this https://i.imgur.com/gybUXeJ.png but from the code it reads as game admin command but i cant get it to work so they can use !claimtickets and it will add x amount of tickets to the person
as in it's not registering someone sent the command?
I'm am once again trying to repurpose code I've already written from a different tutorial but am having trouble editing it
I'm using this code to move a selection arrow up and down on a list. Only problem is, when the aspect ratio changes when the menu is open, it becomes misaligned. If the aspect ratio is changed, and the pause menu is closed and reopened, it works as expected. It only occurs when the aspect ratio is changed while the pause menu is open.
The pause menu is a canvas, set to Screen Space - Camera, with an orthagonal camera.
this method force UI's to adjust, not sure if that was the problem though
to be clear, you do want the AddItem command to only change the FIRST null item in the slots list, correct?
you seem to be mixing up yout slots and itemSlots variables
the first available. So for the first object, fill the first slot, if first slot full, fill the next available slot
I have a related problem I think I'm realizing, if the player presses enter on the Options menu, it also applies one instance of hitting enter to the first option on the options menu itself. So it essentially treats inputs that open submenus as double inputs
which is what I described (considering empty slots are null)
also the length of a list is .Count, not .Length
lol, even google giving my unity2017 docs by default
it was because of navigation in your button ig
then yes
check your button's navigation and turn it to none (if you have it on, and also have your own script that does the same, it double clicks)
This is the function that handles that
It may or may not be very cursed this is my first attempt at a full UI
I know I already made a similar thing, but nothing happens when a gameObject is on a certain point on the y axis.
oh, tmp thingy, cant help in there
tmp?
textmesh pro
What's that?
Oh that's a leftover pass actually I changed how I handled that
yea nvm realized it's irelevant
now that I'm looking over it again, should my AddItem go in Inventory or InventoryManager?
are you sure that method is called twice? Put logs in there first
yeah the function is only run once
it just resolves activateOptionsMenu(), then in the same game step, resolves the if activeMenu "Options"
so I need to add a break somehow
use returns instead of break then?
after activateOptionsMenu()
or actually, just use else ifs
makes life simpler
adding a return after the switch worked as well
might refactor it for else ifs later
but fixing that didn't solve my aspect ratio arrow misalignment issue sadly
I tried binding the aspect ratio changing function to a key, and it doesn't break in that instance. It's only when I activate it in the mainGameManager that is misaligns
reading those now
I'm a little confused
how do I call the method?
the only code it gives is declaring it?
why would I need to declare a unity built in method

ForceRebuildLayoutImmediate(yourMainPanel'sRectTransform)
there's some using for it afaik
you mean the canvas? What's a "panel" in this context?
it also says the function does not exist
LayoutRebuilder.ForceRebuildLayoutImmediate(mainmenu.transform as RectTransform);```
not the canvas, just your mainmenu thing
Your member variable(s) here are slot, and itemSlots is just a local variable to define the components. Your InventoryHandler script may not be setup correctly if you're using it as a singleton.
alright i asked this yesterday and i got some help but i am still struggling immensely, i need to know how to acess a variable from a different script
- i have one script with
public int Money = 1on a box - i have another script that has i want to access the money on so i can add and subtract it using that box
i have no idea what im doing 😭
Reference the other object with the script.
dude i been TRYIN but i dont know what that means mannn
These are some of the best ways to reference game objects in the Unity engine. There are other methods of getting a reference such as the GameObject.Find and GameObject.FindObjectsOfType methods, but those methods are generally slow because they need to traverse the hierarchy to find the object and you don't get to choose which object it finds i...
alr ill watch this and come back if im still somehow confused 🙏
I think I linked this yesterday.. but just in case I didn't:
https://unity.huh.how/programming/references
You want a serialized reference if possible
yeah you did but im still at a loss cuz my reading comprehension is negligible
yeah im still having issues like i can get the serialize field thing to open but im not sure what im supposed to be putting here
hold on lemme try smt before
yeah no i think im just braindead 😭
You put an OBJECT with the script you want into it. You can't put in a script itself
So like:
public MoneyScript money;
Then you drag an object with the MoneyScript into that field
ok first off which object am i putting the serializefield thing on, the one with the money variable or the one i want it on?
ok hold on
i thinkk i got it
lemme test
You need to make a field that's public or serialized with a type that's the script you're wanting to access.
so i switch out MoneyScript for the actual name of the script right?
Next using the inspector, drag and drop the other object with the script into the inspector-field.
but my goal is to subtract stuff from it and when im trying that out it says i cant because its not an integer anymore or smt?
That doesn't matter. Get a reference to the script from the other object first.
i have that part here man
money = target controller? 🤔
Now you should be able to do Money.Money -= 1
the money int is on the target controller script thats why
very confusing but gotcha
Assuming the integer field is called money as well
well cuz you gain money by hitting the target so
I think you might be having a hard time understanding references, by your choice of Money variable name.
what else would i name the variable representing money if not money
does -= mean +?
Typically when you want to reference a script, which is what you're doing, you write the same name, just different casing. You're not really referencing money (although you are able to access that), you're referencing the script itself.
So MyScript.cs , the reference would likely become myScript.
Then from there, you access myScript.money.
It doesn't matter from a functional standpoint, but it's clear you don't quite understand what you're doing here just by the naming.
Hopefully that helps clarify a bit.
It's a shorthand for A = A - 1
oh ok ty
because for example, you could also do myScript.bankAccount, etc. it's not just money.
that does not infact clarify it because i do not infact understand what im doing generally
Start a thread and I'll explain if you actually care. Otherwise, all good.
I don’t want to use the InventoryHandler but I was sure how to rewrite the script to not use it
Your slots will handle the update of individual UI elements themselves when you start adding/removing from them.
if(slot.item == null)
{
slot.item = newItem;
slot.image = newItem.image;
slot.text = newItem.text;
}
it's setting it.
slot is the one checked though
(i didnt read any further above) lol
if slot is null, slot.item is null too
sorry I mean slot is always set
it's the item that is null, also text is probably the quantity which is more than just setting the text but appending values
ah yea
Ah, all good now 
i see now
can I send what my scripts currently have? I have to update referenced names but I want to double check the logic before I try and do so
Throw it on a paste site and post it
📃 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.
The old inventory script can be discarded as the new one replaces it completely.
Hello, how does the Raycasting function work in unity?
Inventory.cs or InventoryManager.cs get rid of?
InventoryManager.cs
It is a spatial query that returns true or false if it hits a valid collider
What specifically would you like to know more about?
How i use this?
Depends on a lot. 2d or 3d?
Want it to only hit certain things?
What will it be used for?
3d
Here is the 3d one
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Ok
Thank you
InventoryManager.cs
What would be a good way to get the number value of a keypress? (Say the user presses 4 and this magical function returns the int 4)
New input system or old?
new
With the old, you could probably do a loop with every possible key etc
yeah I was hoping there was a more elegant solution than a big loop or if else tree, but if thats the way it needs to be done its not the end of the world
By far the best option is to create 10 actions and just map them to the numbers
This gives you full support in the system including rebinding etc
I'll definity give that a go, thank you!
would a state machine for movement and attack something like this be ok or no?
Should movement and attack be seperate?
Or is there a better way to do chain attacks?
is there transition from jump attack1 to idle (or other state that can go back to idle)?
Oh yeah, now that i think about it every state actually, if you don’t continue the attack or grounded after jump/jump attack
I am having some issues with collisions using 2D box collider and rigidbody. This is a snippit of my code for detecting things on the solidObjectsLayer i've defined that i do not want to walk into.
It "works" but my character get stuck on the object and screen starts bouncing
Here is the rest of my movement code
For one thing, you never want to do input in FixedUpdate
The coroutine that you start every time you can move is concerning. You are gonna be starting it multiple overlapping times it looks like
if i drop the coroutine and swap IEnumerator to just void, i get a vector 3 error, not sure what to do about that to be honest.
I may need to redo my movement code, i was able to get it working with different code, it just functions differently than i'd like, I want it to be very old school "tile movement" moving 1 position / coordinate at a time, rather than the "fluid" movement when i use the code that i have commented out.
I did miss the IsMoving bool
So that should negate the issue I mentioned
No one knows what a "Vector3 error" is. You need to provide a bit more details.
yes, isMoving is set to no by default.
sorry thats at the top, only sets to Yes when Move is called, then No again at the end of the method
What line is the error thrown at?
You can't use yield in a method with no return type
It seems like it was a coroutine before, but the same code wouldn't work as you expect in a normal method.
Rofl, well. the collisions work without the coroutine, but
my character is moving like 1000 times faster
Yes, because you're moving it right to the target position within that Move method.
Here's a secret about how computers execute code: they do it line by line. Untill your Move method gets you to the target position, it wouldn't let unity update.
Well, i do want to move to that target position, rather than a smooth movement, i want the movement to be very gridlike (think pokemon, old school final fantasy, etc.)
In this case you need to decide on a fixed rate at which you move your character between the points.
But here's secret #2:
Collisions wouldn't work properly if you move the object in a physics incompatible way, like you do.
Well, thats what the isWalkable bool method "should" be there for, maybe that is what isn't working properly.
Well, with your current code this runs once, then you move your character to the target designation in one go, then unity updates and it runs again, but your character is already at the target.
Though, I guess the target is just the neighbor tile
if i remove the rigidbody and box collider 2d from the player, it will work also, but then i have issues with triggering scenes, (entering a town, etc.)
I'd assume that the overlap isn't working as you expect. What's with that .1 radius?
It's probably smaller than your character.
I played around with different values to get it working before i started adding my triggers, .1 seemed to be the sweetspot for the isWalkable method at the time for my character to slide just in between tiles, i then came accross an issue with triggers not working at all unless i put a 2d box collider and rigid body on the character, which now that i've done that, the fricken colliding isn't working
Wouldn't that detect the tile too late? You need to already be within the non walkable tile for it to return true. Is that what you want?
well im passing it into a variable to see the "next tile" with var Target pos = transform.position; and targetpos.x and y += input.x and input.y
at least thats what i imagined it would do lol
Try asking in #💻┃unity-talk
This is the beginner coding channel.
Ah, right. That part should be fine then.
Hi ! Is there a way to have a dropdown with a function on "changed value" with argument and each selection on dropdown have a different argument ?
like, i know how to get the value of the selection and i know i could have a case statement, but is there a way to do it easily ?
Assets\Scripts\Tool Data\WebSocketHandler.cs(3,7): error CS0246: The type or namespace name 'WebSocketSharp' could not be found (are you missing a using directive or an assembly reference?)
I don't know how to fix it, since the "using Websocketsharp" is working perfectly fine in the code itself with no errors. This only comes when i try to build.
I'm having difficulties with Unity's JsonUtility. I try to retrieve a list of objects that I have already defined, but it does not recognize it. I'll put the prints below. The first image is the format that the json comes from the api. The second and third image is how I left the classes to receive this json. The last image shows how I am receiving after from the request.
to start with your classes do not have the Serializable attribute
ohh thx, it was that
...
I know that there is code examples to clamp the rotation of the camera after the input but is there a way to do Clamp the rotation based on its current rotation?
currentEuler.x = Mathf.Clamp(currentEuler.x, -_settings.MaxLookY, _settings.MaxLookY);
// Debug.Log(currentEuler.x);
transform.localRotation = Quaternion.Euler(targetEuler);```
i want that when my bullet collides(using on trigger) with someone having Enemy tag then it should get destroyed and based on that totalenemies variable should be -= 1
and this collied script is attacted on all 5 enemies
and i created a new script named manager which basically finds all the gameobjects with tag enemy in to my list named enemies and i just equated totalenemies var with enemies.length and debugged it and its showing 5 but after shooting on enemies its showing null reference error
Hello guys, I have a simple card drop system. For example I have Cards A, B and C, but I dont wanna drop them by equal chance. For example Card A, 50%, card B, 30% and Card C 20% . Can anybody give me the general idea of how to do this!?
use weight system
hmm never heard of that
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Wishlist Veil of Maia! - https://store.steampowered.com/app/1948230/Veil_of_Maia/
Wishlist Samurado!
https://store.steampowere...
In computing, the alias method is a family of efficient algorithms for sampling from a discrete probability distribution, published in 1974 by A. J. Walker. That is, it returns integer values 1 ≤ i ≤ n according to some arbitrary probability distribution pi. The algorithms typically use O(n log n) or O(n) preprocessing time, after which random ...
if anyone can help i would highly appreciate it
you need to show code
can someone help :P
#854851968446365696 how to share code
is there any way to find all the currently down keys in a list instead of having to search for every key with a long ass if/else if statement?
use new input system
!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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreManager : MonoBehaviour
{
public int totalEnemies;
GameObject[] Enemies;
// Start is called before the first frame update
void Start()
{
Enemies= GameObject.FindGameObjectsWithTag("Enemy");
totalEnemies = Enemies.Length;
Debug.Log(totalEnemies);
}
// Update is called once per frame
void Update()
{
Debug.Log(totalEnemies);
}
}
oh ok wait
Thank you so much
its working i just forgot to assign it
so what if i want to spawn objects
like this find gameobjectswith tag is in start
what do you want to do?
how is that related?
oh, you wanto spawn enemies
and add them into the array of enemies?
yes
i'd just make the ScoreManagre a singleton, and in the Enemy class in Start() add them to the array of enemies
so each enemy add himself to the array
instead of the ScoreManager looking for every enemy
how to achive it?
google it
oh its a thing
then after you have a singleton from ScoreManager
in your Enemy, in Start() just do ScoreManager.Instance.Enemies.Add(this)
and make the Enemies a List<Enemy> not an array
you cannot add elements to the array dynamically in an easy way, just use a List
{
_currentModifer = Mathf.Lerp(start, target, time / duration);
time += Time.deltaTime;
yield return null;
}```
How would I be able to implement an AnimationCurve.Evaluate into this loop?
depends on what are you trying to achieve
Its a recoil coroutine, so for the recovery I want to have it start veyr slow then quickly ramp up to reach its target
Basically similar to pulling the gun to its original position after firing
so you want to modify the currentModifier value based on the animation curve?
well, make a animation curve (obviously)
yea but where do you plug in the animation curve?
nope its a coroutine
good
then i'd do something like that
float time = 0f;
while (time < duration)
{
float curveValue = recoilCurve.Evaluate(time / duration);
_currentModifer = Mathf.Lerp(start, target, curveValue);
time += Time.deltaTime;
yield return null;
}
just evaluate the curve and use this in the lerp
that works too
i wonder if its better to just instead of having two coroutines for the recoil and the recovery. what if I just do one coroutine that uses a curve such as this? Is that common? This way I get both the recoil and recovery in one value.
going to try it actually
hi guys, im instantiating a missile here but i want it to point forward. but for some reason, it always points in a different direction depending on my spider rotation and forward
and here is the prefab im cloning
It looks like it's just the original orientation of the mesh that is wrong.
it looks like it worked magically after 200 tries on different line of code and then going back to the beginning
The Z Axis (Blue arrow) on your missile is pointing out to the side, so that would be the missiles 'forward' direction. Generally you would create an empty to be the 'root' of the prefab and then make sure all the rotations of the child objects (missile mesh/particles etc) are rotated to align to the empty.
or set the transform.right
but if i change it change the pointing direction :(
its velocity is just its updward direction now, its fine i think
hey everyone, im trying to make wheels that rotate depending on the velocity of the car, but as soon as the wheels rotate 90 degrees either direction they just kinda stop?
visualWheel.localEulerAngles = new(visualWheel.localEulerAngles.x + wheelVelocityLS.z, steerAngleLerp, 0);
this is in FixedUpdate()
I wanna start on a game where the character just falls down a huge pit and if it hits something it dies
The walls should be collidable, so you can't go through them
The floor should be collidable and trigger character death
What's the best way to set up these collisions? Since my character won't be interacting with the collidable objects most of the time
Just have it so if it collides with floor it will call a method which does what u want when it dies. And the character has a rigid body that u probably want to control using wasd
And add just colliders to the 3d objects
that is not valid code
yeah it is
C# 9 feature, really interesting one, I havnt seen it used often but if the left hand type is known, the right hand side doesnt need the type again when newing it, same with default and default(T)
if it stops turning it probably means that localEulerAngles.x + wheelVelocityLS.z is 0. What exactly is wheelVelocityLS.z? I think your local angle goes from 0-360 and your wheelVelocityLS.z goes from -180 to 180, so when the wheel is at 90° you set x to 90 + (-90) = 0. Try adding 180 to the second value. Also, if it is a quarternion you might want to read it's eulerangles instead @stoic spear
Recommend not trying to read euler angles from the Transform, it always leads to these issues
why is my car keep getting teleported higher than my set hover height? and also when the car is higher than desired hover heihgt its not getting pulled down it just stays up there
i wouldn't do that personally
as when it's splitted you have more controll over what are you doing
and you can fire additional events such as OnRecoil, OnRecovery etc
with one coroutine it will be harder to achieve
This is a code channel, #📱┃mobile is where to ask for help with building for Android, but with actual specific questions
guys, does somebody know how WaitforSeconds works?
Yes, lots of people do
i believe they just maintain a timer inside and update it in each foreach call...probably complicated than what i through
btw show you !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.
Show your code and explain the issue, that'll help you way more than just asking about them generally
you probably used it wrong, share script
a powerful website for storing and sharing text and code snippets. completely free and open source.
the issue is I want that once an object collisions with my player it inverts controlls (speed is set negative)
before i start coding a* pathfinder should i create a graph in my game
i havent completed the code)
but I want it to wait 5 seconds until having the controlls normal again
You need some nodes to traverse yes. It could be a simple grid
is the log printing?
IEnumerator VuelveNormal()
then the coroutine is never started
sorry, Im a little noob. Is the coroutine the same as a method?
yes I mean theorically the StartCoroutine is like a mention to call a method
if Line 42 is not printing the coroutine was never started
so how can i assure it starts?
It is a method to start a coroutine
This object wouldn't happen to be on (or a child object of) Tuerquita, would it?
it is not child object of anything
are you sure its active the whole time?
So, the InvertManager object is never destroyed or disabled?
it is destroyed once it contacts the player
oooh
i had unable before the Coroutine thing
could it be that?
If an object is destroyed or disabled, all coroutines currently running on it are canceled
Does it print the first debug
if it doesn't print the first one, then that code is never run
Either the condition is never true or the OnTriggerEnter2D itself doesn't run at all
I am trying to assign a material to a 3D object plane but the plane is still transparrent for some reason. Anyone help please?
If the first log doesn't run, then the StartCoroutine line is never reached
not a code question
the one inside the IEnumerator you mean right?
Ok, tell me where to put my question then.
If the first log doesn't run, then the StartCoroutine line is never reached
this is wierd. I put the setactive(false) into the coroutine thing and it executes but not the debug
then you probably have debugs collapsed or somethin
but it doesnt set the speedvalue to the normal one either
apologies to be barging in, but i cannot figure out for the life of me why im not getting a console output from this?? (the interaction system is ripped straight from a tutorial so i dont think anything is wrong there, it works and gives console outputs with a test script i made)
more info is probably needed, ill be happy to provide
oh right, Plaque is a super simple struct i made (still just learning about OOP)
Show a screenshot of your full unity window, with the console visible, after this is supposed to have printed
why are you looking for IInteractable but script is called PlaqueZero?
if IInteractable is an interface it shuld be implemented in PlaqueZero
yep, thats the issue
thank you!
very stupid oversight
it needs to be there after : MonoBehaviour like it is in the other script 🤦♀️
yeah thats what makes Interfaces modular
you can add as many as you need to a class eg public class Foo : MonoBehavioir , IInteractable, ISaveable, IDamagable
code works now
what is this
it means you added something new to prefab thats not on the original
oh okay
new file in version control
is it? ohh
which means...
which means you created a new file and haven't committed it to the repository yet
okay, now on to getting ui to pop up when the variable is true (this is a very stupid way of doing things because i'll need a separate script and separate ui element for each of the 50 plaques i have, but if its stupid and it works its not stupid)
or you added something new to a prefab 🤷♂️
I'm not actually sure because I don't use Unity version control integration
huh could've sworn they were green 🤷♂️ but yeah i dont use it myself I just recall the prefab + icon in 2022 changed
IEnumerator VuelveNormal()
{
Debug.Log("entraenIEnumerator");
_myManoloMov.speedValue = -_myManoloMov.speedValue;
Debug.Log("antes de wait");
yield return new WaitForSeconds(5f);
Debug.Log("pasan5secs");
_myManoloMov.speedValue = 0;
} when the code gets to the yield return, the rest of the code doesnt work
why??
the debug, for example, doesnt execute
If a coroutine stops at a yield and never resumes then either:
- You set Time.timeScale to 0 or a low number somewhere
- The GameObject that was running the coroutine was deactivated or destroyed
- The coroutine was stopped with StopCoroutine
okay, let me try, thanks a lot
i checked and i dont do that in any part of the code
You'd have to show the code
and explain what this code is and how it's working
where the coroutine is started from and how
etc
visual studio
then its not what they asked is it?
oh okay
the error there is not the problem
ive been having this error there for a while
Fix it anyway
It could be
When an error occurs, code stops
At the very least it'll make the console cleaner
You can't know that this script doesn't throw an error because the console is flooded with errors from the other script
Sorry if this is the wrong place - I'm mostly new to unity and very new to this discord, but I am an experience C# dev so not sure if this is the correct place to ask
I'm trying to write a custom editor that at its heart will store a set of selected prefabs + some misc data associated for use in runtime code later down the line, I've never done any kind of state-based stuff in Unity and at first was going down the line of storing my data as JSON, but I've since read that changing my classes to be ScriptableObject's would be more appropriate, but it doesn't seem to behave like I would expect.. infact, the behaviour is very odd and I dont fully understand it, and I'm struggling to come up with the correct terms to google
So, I have a "tileset" ScriptableObject, code here: https://hastebin.com/share/bafolonoge.csharp
That has a List<tiles> property, tiles being another ScriptableObject that has a GameObject field called tilePrefab, code here: https://hastebin.com/share/okidizugim.csharp
I then have a TilesetEditor class that inherits from EditorWindow, basically I want this to be able to take a TileSet in my assets list and let me modify the linked prefabs and such from within the unity editor, code here: https://hastebin.com/share/icohusuger.csharp, then for debugging I have a TilesetInspector class that just adds a "Tile Count" to the inspector window when I click on the TileSet object in my assets folder.
With all that out the way, I think the way I am saving the connection to the prefabs is somehow wrong... right now I don't know if its in the way I have set up my Tile object, or if its how I've scripted the editor to allow editing it, but I've tried a few different iterations of this and cannot get it to work.
When I open my editor, I can add tiles, the tilecount in the inspector goes up, hitting save in the editor causes my .asset files modified time to change.. but closing & re-opening unity resets the ScriptableObject to empty
Now that I typed that all out I'm not sure it can be to do with the Tile object, since regardless of if its a GameObject or some other abritrary property I am setting, its the List<Tile> that resets, not the tiles themselves... is it to do with my constructor on TileSet to initialise List<Tile> = new List<Tile>() perhaps
do you know what the error could be
The variable health of HealthManager has not been assigned.
You probably need to assign the health variable of the HealthManager script in the inspector.
there isnt any variable in the inspector i can assign
When you change an asset via code you need to tell Unity to save the changes. EditorUtility.SetDirty(yourSO);
Is health private?
You could use [SerializeField]
Show the inspector for HealthManager
Then you have a different instance of the HealthManager script where it is not assigned
Type t:HealthManager into the hierarchy search bar
Yeah i do that - theres a save button in my editor that calls
ah ye, constructors don't work for MonoBehaviours and ScriptableObjects
gotcha, how best to initialise the list? Just check if its null in my editor before accessing it I guess
If you look at the basic examples for custom editors there's some bookkeeping I believe oyu're missing:
https://docs.unity3d.com/Manual/editor-CustomEditors.html
i.e. the serializedObject.ApplyModifiedProperties(); bit
notably you're doing the SetDirty part before rendering the tiles list
I don't use auto properties but if you write it out fully you can say:
[SerializeField] private List<Tile> tiles = new List<Tile>();
And it will never be null
yeah fair - I did try that first and when it wasn't working moved to a constructor - will revert to that
That at least gives me something to look into - thanks
not sure what you mean by this part though - the SetDirty is only called from a button press in the editor
I think that's also why it reset, because the field isn't actually serialized.
it exits the IENumerator before executing the 2s wait time, I dont know what to do
right exactly - you need to do the applying of changed serialized data constantly with the ObjectField stuff. Realistically this direct manipulation you're doing of the object is not best practice. In an editor you're supposed to interact with the serialized objects through thte SerialzedObject API and then applying the changes
I see, I figured I was probably doing something wrong in the manipulation for it to be doing this weird persists during session but not on editor restart thing
When the gameObject that runs the Coroutine gets destroyed the Coroutine will stop as well
I kind of want to only set dirty at the end though, since later down the line I want to validate some basic rules on whats been edited before saving it
rather than each time a property is changed
but in my script it doesnt get destroyed
oh okay
nevermind
Did you figure it out?
yes bro thanks a lot
serializedObject comes from inheriting Editor right? I'm inhereting EditorWindow and getting to the scriptedobject asset via a EditorGUI.ObjectField being populated, so I don't think I have access to that?
however now i have to figure out how to make the object dissapear whenever it touches the ground without not making the wait time to occur
you can wrap your ScriptableObject in a SerializedObject in OnEnable and use it:
SerializedObject serializedTarget = new SerializedObject(mySO);```
Ah cool thanks, ill try going that route
disable the spriteRenderer on it
Can anyone tell me why my second slider is not updating the value placed on it? Follow the prints.
Not sure what you mean. Disabling the renderer would be near instant. It'd SHOW on the next frame, but the command wouldn't lag anything
isnt the excess of gameobjects a cause of lag?
Maybe, maybe not. You can have a lot of gameobjects. Always profile
Creating and destroying is more costly than enabling disabling usually. To an extent
Which is the justification for pooling
This is a mess. Just directly reference these things in a script on the telaEditar object and simply call a function on it
you shouldn't be reaching deep inside other objects like that
and you can't rely on any specific ordering for GetComponentsInChildren
@summer stump the course doesn't have what you call "non primitive data types"
i got to methods, and after them there is only OOP
It does. It talks about classes and structs
Non-primitive Types is what I said
so those are OOP?
And it's a phrase I made up on the spot to just mean anything other than primitive types
No
OOP represents a programming architecture. It uses inheritance and abstraction
i'll go on with the course and figure out on my own lol
and classes?
No. Classes can be used in OOP and compositional architectures.
Classes are an example of a TYPE though
i thought they were cuz when i did the python tutorial, the guy said "we'll be talking about object-oriented programming"
You use classes in OOP for sure.
You make a base class, you inherit from it to extend the behaviour, and bam, that's OOP.
But you also don't have to inherit. You can make each class do a small part and just combine them to make a cohesive and modular whole. Bam, that's composition
Why can’t i drag a script into my player prefab
okk ty
a question
if "function" are called "methods" in c#, how are the "methods" (the ones followed by the dot) called?
you can't add script from the scene unto objects in your Assets
members
Methods are just functions that are in a class or struct
Not sure what you mean by the ones followed by a dot.
If you mean dot notation, it's just how to access members (whether those are fields or methods themselves) as gruhlum said
They are called methods in c# too
but methods are function
Same as python
I use python too btw. Quite extensively
The difference between a method and function is scope
ok?
lol
it's obvious that if i don't study i will be confused
my english sucks tho, sry
No you're fine! Nothing to worry about
Not sure how to stop the value boxes from appearing to the side like that. Or how to configure the massive gap
what type of field is this?
It's a PropertyField
Can a static Rigidbody gain velocity?
No
no
This type of Rigidbody2D should never repositioned explicitly. It is designed to never move.
What if I constantly set it's position to another gameobject, which is moving?
Then it is teleporting with no velocity
At each position, it is not actually moving. It is just set to a new non-moving position
But really, why move a static rigidbody?
If I use the I key to run the function changeAspectToClassic() in the camera script, everything functions as intended.
If I use the menu to run the same function from the main game manager script, the selector arrow, which is a TMP, becomes misaligned with the rest of the menu until the meny is closed and reopened
the function in question
What does RescaleCamera() do?
!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.
Here's the whole aspect ratio handling script
and, as may also be relevant, all menus are on their own canvas, and the selector arrow is on its own dedicated canvas so it can be shared between all menus. All elements on menu related canvases are anchored to the center of the screen
how do you move the selector arrow?
here's the up function, down is identical but in the other direction
it gets the Y axis position of the targeted menu element, which exist in arrays
Do you call this every frame?
no, it's only called when either directional button is presset while paused and with an active menu
why is my car keep getting teleported higher than my set hover height? and also when the car is higher than desired hover heihgt its not getting pulled down it just stays up there
nice gpt code
