#💻┃code-beginner

1 messages · Page 66 of 1

obsidian parcel
#

spikes is this one right

rich adder
#

expand the arrows untill you see the cause of high ms/gc alloc

obsidian parcel
#

okay

rich adder
#

EditorLoop is the unity editor

obsidian parcel
#

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?

rich adder
#

you would be able to see if the editor is just causing too much overhead

wintry quarry
obsidian parcel
#

aight will surely look into it

swift crag
#

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

rich bluff
#

yes editor eats performance

#

its a hungry beast

swift crag
#

nom nom

#

fullscreen the game view to get a better idea of performance

rich adder
#

esp when you have lots of gizmos xD

rich bluff
#

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

sharp wyvern
#

not sure if it's been mentioned yet: remove all Debug.Log command before profiling- these can get SUPER slow.

rich bluff
#

right because those get sent to editor console which also hogs like crazy under spam

queen adder
#

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

rich bluff
#

never heard about that game, but common place to start is ScriptableObjects and Prefabs

queen adder
#
StrategyWiki

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

queen adder
#

im quite allergic to making many files, idk why

rich adder
#

why would you need many files with SO ?

verbal dome
#

Because each SO needs to be in its own file

#

To get serialized properly

sharp wyvern
# queen adder https://strategywiki.org/wiki/Dragon_Warrior/Spells

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"

queen adder
rich adder
#

but can create many SO from 1 file

sharp wyvern
rich bluff
#

not necessary

queen adder
#

second approach im thinking is a SpellLibrary and reflection, but is quite nasty

rich bluff
#

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

queen adder
#

that too, then switch?

rich bluff
#

yes switch is the last option

#

there is also a visual spaghetti option

queen adder
#

i had a custom unityevent approach before, but it was painful to set up

rich bluff
#

you dont have Odin?

queen adder
#

    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

rich bluff
#

you can use type reference but then no per instance parameters

queen adder
#

type reference?

#

hmm.. ig imma just go with simple, partial class holding an enum switch

rich bluff
queen adder
#

nothing's ancient

rich bluff
#

same thing microsoft is doing in its libraries with TypeID attribute

fallen lance
#

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

rich bluff
#

attach guid to any type with attribute, serialize that guid, and you will never lose a reference to that type

queen adder
#

is this repo like SerializeReference?

rich bluff
#

it is specifically a serialized Type

queen adder
#

lemme try the demo

queen adder
#

I think it's incompatible in my unity

thick mortar
#

who can help me with a certain issue

fossil drum
thick mortar
fossil drum
thick mortar
#

come onnn its argent

rich adder
#

if its urgent you would spit the out the question instead

rich bluff
#

(joke)

rich bluff
#

what is that file?

swift crag
queen adder
rich bluff
#

just create new one

queen adder
#

interesting

#

if I use this SO, it automatically makes a new instance of the Ammofreezing?

rich bluff
#

i dont know what it does

queen adder
#

u wrote it

rich bluff
#

the reference just will return you the type

#

use Activator.CreateInstance(referencedType)

queen adder
#

this can be accessed with ```cs
SO.ClassToSpawn.AmmoFreezing();

rich bluff
#

no

#

ClassToSpawn is Type

#

not an object

sharp wyvern
#

hunh? A System.Type IS an object

queen adder
#

so this SO kinda need a supporting field that accepts an Ammo object?

rich bluff
#

yes but its an object of type Type not of the end type that has method AmmoFreezing

verbal dome
#

It just allows you to serialize a System.Type

#

Right?

rich bluff
#

yes

summer stump
queen adder
#

this is the selling part, I see

sharp wyvern
#

var

rich bluff
# queen adder so this SO kinda need a supporting field that accepts an `Ammo` object?
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();
    }
}

queen adder
sharp wyvern
# queen adder

Sorry being silly: I avoid ''var'' like the plague. never clear what it is.

queen adder
rich bluff
#

after a while it just stops being an issue

timber tide
#

yeah totally var that

queen adder
#

[ExposeType("deliberateGibberishHereCanBeUsedOrStandardGUIDGenerator")]``` it doesnt matter what's in here right?
sharp wyvern
#

hard disagree

rich bluff
#

and never changes

sharp wyvern
rich bluff
#

assembly qualified name will suffer from all the issues any other type of serialization except attribute suffers

timber tide
#

Reminds me that I need to change some data structs to IReadOnly for my immutable SOs

sharp wyvern
#

what kinda issues?

rich bluff
#

renaming your types will break serialized data

#

moving into different namespace

sharp wyvern
#

oh! yah, totally

rich bluff
#

[assembly: BindTypeNameToType("MyOldNamespace.MyNewTypeName", typeof(MyNewNamesSpace.MyNewTypeName))]

#

you will still need to use attributes when you will be renaming types

timber tide
#

"Odin's variant was added to support the rare (and not recommended!) case of property serialization."
teehee

rich bluff
#

yes, rare

timber tide
#

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.

queen adder
#

cant it work with this set up? Every class need it's own attribute?

rich bluff
sharp wyvern
#

AND they must be unique

rich bluff
#

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

queen adder
#

most reliable id generator

fickle plume
#

@sharp wyvern No reaction gifs, please

sharp wyvern
#

fun

sour hound
#

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

twin bolt
#

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.

slender nymph
#

well that's certainly not how you check if a number is within a range.

twin bolt
#

I fixed my issue, but how should i do it?

slender nymph
#

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

buoyant knot
#

yeah, you should actually do two inequalities

#

==/!= with floats is bad juju

eager elm
solemn fractal
#

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?

timber tide
solemn fractal
eager elm
cosmic dagger
solemn fractal
#
private BossOne _boss;
//on start
_boss = FindObjectOfType<BossOne>();
/onTriggerEvent
        if (other.tag == "BossOne"){

            _boss._bossOnecurrentHealth -= _playerBulletDamage;
            SpawnTextAboveHead(_playerBulletDamage);
            Destroy(this.gameObject);

        }```
timber tide
#

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.

eager elm
cosmic dagger
solemn fractal
#

hmm ok thank you !! will try

eager elm
#

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.

calm coral
swift crag
#

what? that code is completely fine

calm coral
swift crag
#

Oh, I see what you're looking at.

#

You're talking about comparing it to null

calm coral
swift crag
#

That much is right.

#

I would not say it's the "wrong way to get a component"

cosmic dagger
swift crag
#

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

calm coral
swift crag
#

correct idea, just worded weirdly :p

#

so yeah, you're right: the code is not correct

#

TryGetComponent is the way to go here.

calm coral
swift crag
#

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

solemn fractal
# eager elm FindObjectOfType() could get either of the bosses and not the one that is going ...

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

eager elm
solemn fractal
#

ok thank you very much.

languid gate
#

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);
        }
    }
}
short hazel
languid gate
timber tide
#

whatcha colliding with

languid gate
#

the player object with the tag "Player"

short hazel
#

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

languid spire
#

you have 3 LogWarnings there but you have hidden them

short hazel
#

lol

#

Yep

gray bough
#

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

short hazel
languid gate
#

:/

#

man

#

i am blind

#

thanks lol

sage mirage
#

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?

timber tide
gray bough
# gray bough Does anyone mind helping me with some script code? I'm following a tutorial for ...

`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

summer stump
#

Looks like you modify the list while iterating it?
Oh, ItemContent is a transform, so you're destroying children? (Lol)

gray bough
eager elm
summer stump
cosmic dagger
timber tide
#

Destroying, instantiating, then using find on that same exact GO is quality

gray bough
# eager elm jesus christ, that code is from a tutorial? Mind sending me a link?

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...

▶ Play video
eager elm
gray bough
languid gate
#

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

gray bough
summer stump
sage mirage
# timber tide If it exists between all scenes (DDOL) then deleting it will delete that specifi...

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.

eager elm
timber tide
granite raven
#

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");
}
}
}

cosmic dagger
eternal falconBOT
gray bough
cosmic dagger
eager elm
# languid gate

the error tells you why it's not working. You need to add a DialogueTrigger to your player gameObject

cosmic dagger
# gray bough
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 . . .

granite raven
#

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!!!!

cosmic dagger
eager elm
timber tide
granite raven
ruby python
#

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 ?

gray bough
granite raven
ruby python
#

Thank you.

cosmic dagger
ruby python
#

🤦‍♂️

languid gate
# eager elm Why? Why what?

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

summer stump
gray bough
cosmic dagger
eager elm
granite raven
languid gate
# eager elm That error is generated from your code, or the code you got from somewhere. Doub...

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.");
        }
    }
}

}

granite raven
#

@cosmic dagger

languid gate
#

ok i now know how to fix it thanks 🙂

eager elm
short hazel
#

Oof yeah, I'd just use a Debug.Assert() in Awake or Start for that

#

Debug.Assert(thing != null, "your error message here")

languid gate
#

but thanks for the advice ill do that next time

granite raven
#

any clue and how to fix the reference error?

timber tide
#

By giving it a reference and making sure it's not null

languid spire
granite raven
granite raven
languid spire
#

on the line you indicated playerRB or focalpoint could be null. check it

sage mirage
#

Hey, guys! If I want to get reference for a specific scene in my game how to do that?

delicate portal
#

Why are the objectHitRenderers are null?? Everything seems perfect, and when I debug the meshRendererArray it shows all of the renderers

sage mirage
granite raven
sage mirage
#

When I am making a scene in my game that scene

eager elm
languid spire
eager elm
sage mirage
languid spire
#

Also make sure Focal Point is not being deactivated

gray bough
# cosmic dagger ```cs var itemIcon = obj.transform.Find("ItemIcon").GetComponent<Image>(); ``` t...

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

granite raven
# languid spire Check the game object name, make sure there is no space at the end

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

languid spire
eager elm
timber tide
gray bough
timber tide
#

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?

granite raven
granite raven
timber tide
# gray bough I have a set amount (25)

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.

tepid cobalt
gray bough
timber tide
#

What do your slot prefabs look like?

timber tide
#

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.

gray bough
#

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?

timber tide
#

Right, instead of letting the inventory know everything, you break it down so the slots contain their own set amount of data.

gray bough
#

does this script go on the slots themselves?

timber tide
#

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()

timber tide
#

and text would be type of Text or TMP_Text, whatever you're using

gray bough
#

I'm trying to re-use the existing script to fit this situation

cosmic dagger
#

And Image does not have a SetActive method . . .

gray bough
#

yes, i changed the type for icon and am now trying to update everything

timber tide
#

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

gray bough
#

I am stuck trying to figure out what to change this to

summer stump
sharp wyvern
#

GetComponentInChildren<Image>() ?

gray bough
summer stump
gray bough
#

this is what I have currently

timber tide
#

GetChild returns a transform

#

you want to return a type of Image

sharp wyvern
#

then to access gameObject stuff like isActuive or SetActive use icon.gameobject.SetActive...

wintry quarry
#

you already got the component in Start

#

icon is already an Image

sharp wyvern
#

^ good point

gray bough
#

I took that line out, thank you. This is a script from a different tutorial that I am trying to update and re-use

wintry quarry
#

welll... not the line - you still want the icon assignment

timber tide
#

Wasn't there an enabled method for images specifically or am I dreaming

gray bough
#

this is the whole script

lilac crow
#

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?

timber tide
# gray bough this is the whole script

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.

gray bough
timber tide
#

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.

gray bough
#

Ahhh okay

timber tide
#

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.

timber tide
# gray bough Ahhh okay
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
upper hearth
#

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)

worn ether
#

How's the camera in your hierarchy?

upper hearth
lament silo
#
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)
worn ether
upper hearth
timber tide
worn ether
#

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.

upper hearth
#

So I just want to inherit those head rotations without messing up my camera's looking around feature

worn ether
#

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

timber tide
upper hearth
timber tide
worn ether
novel shoal
#

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

lament silo
gray bough
summer stump
novel shoal
summer stump
#

Then drag in the script

eternal falconBOT
#

:teacher: Unity Learn ↗

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

novel shoal
#

i am doing a tutorial

summer stump
novel shoal
#

but i wanted to try to do something with what i know

timber tide
summer stump
summer stump
# novel shoal sorry

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

gray bough
summer stump
novel shoal
#

@summer stump

gray bough
#

w3school is a website

novel shoal
#

oooh

gray bough
#

they offer different courses for languages

worn ether
#

freecodecamp has some good ones too

gray bough
worn ether
#

they released a C# certification course recently

novel shoal
#

i know a bit of c#, can i skip what i already know?

summer stump
summer stump
#

Now learn what non-primitives are

novel shoal
#

ok

wintry quarry
#

same with struct and enum

summer stump
#

Just keep in mind that Unity is just a c# api. Knowing c# is the most important part. Then learning unity is much easier

novel shoal
#

i'll learn it

#

i already coded a bit in python so i hope it will be easier lol

summer stump
grizzled river
#

how to make player move script?

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

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

summer stump
#

You gotta choose Character Collider, Kinematic/Dynamic Rigidbody, or Transform based movement

#

Best of luck!

lilac crow
#

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?

crude prawn
#

for instance animator.SetBool("Run", true)

#

need to create a bool in the animator tab and transition it though

granite hedge
#

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!

lilac crow
timber tide
# gray bough variable in the prefab? or somewhere in the script?

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.

crude prawn
#

and drag it to the button

sour hound
#

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

green mirage
#

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

crude prawn
spare mountain
green mirage
#

yea

lilac crow
# crude prawn what do you mean

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.

green mirage
#

sorry no

#

there is not

green mirage
spare mountain
crude prawn
#

when u click a button the run animation is set to true?

green mirage
#

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?

lilac crow
lilac crow
crude prawn
crude prawn
#

gl

green mirage
viscid sparrow
#

Is there a way to prevent pixel art from doing that individual pixel slant thing when it is rotated?

spare mountain
green mirage
#

I don't think so, We have xr plugin installed

spare mountain
viscid sparrow
spare mountain
viscid sparrow
spare mountain
viscid sparrow
#

y'see how it has that weird slant on the pixels? Do you know how to fix that?

spare mountain
#

can I see your sprite's settings?

viscid sparrow
spare mountain
viscid sparrow
#

doesn't do anything

spare mountain
viscid sparrow
#

yeah no changes

spare mountain
spare mountain
#

are you running it multiple times?

timber tide
#

Looks fine for the most part

sour hound
#

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

gray bough
timber tide
minor jungle
#

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

spare mountain
minor jungle
#

its a unity scipt not a discord script

spare mountain
#

you're good then

minor jungle
#

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

spare mountain
minor jungle
#

Thats what im getting so im guessing the code is wrong but i cant work out what

gray bough
green copper
#

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.

spare mountain
# gray bough

to be clear, you do want the AddItem command to only change the FIRST null item in the slots list, correct?

wintry quarry
# gray bough

you seem to be mixing up yout slots and itemSlots variables

gray bough
green copper
spare mountain
wintry quarry
#

also the length of a list is .Count, not .Length

queen adder
#

lol, even google giving my unity2017 docs by default

queen adder
queen adder
#

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)

green copper
#

This is the function that handles that

#

It may or may not be very cursed this is my first attempt at a full UI

tender breach
#

I know I already made a similar thing, but nothing happens when a gameObject is on a certain point on the y axis.

queen adder
#

oh, tmp thingy, cant help in there

tender breach
#

tmp?

queen adder
#

textmesh pro

tender breach
#

What's that?

green copper
#

Oh that's a leftover pass actually I changed how I handled that

queen adder
#

yea nvm realized it's irelevant

gray bough
# gray bough

now that I'm looking over it again, should my AddItem go in Inventory or InventoryManager?

queen adder
#

are you sure that method is called twice? Put logs in there first

green copper
#

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

queen adder
#

use returns instead of break then?

#

after activateOptionsMenu()

#

or actually, just use else ifs

#

makes life simpler

green copper
#

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

queen adder
#

did you read the docs i sent?

#

the method that refreshes recttransforms

green copper
#

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

static cedar
queen adder
#

ForceRebuildLayoutImmediate(yourMainPanel'sRectTransform)

#

there's some using for it afaik

green copper
#

you mean the canvas? What's a "panel" in this context?

#

it also says the function does not exist

queen adder
#

            LayoutRebuilder.ForceRebuildLayoutImmediate(mainmenu.transform as RectTransform);```
#

not the canvas, just your mainmenu thing

timber tide
# gray bough

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.

raven trench
#

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 = 1 on 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 😭
ivory bobcat
raven trench
#

dude i been TRYIN but i dont know what that means mannn

queen adder
raven trench
#

alr ill watch this and come back if im still somehow confused 🙏

summer stump
raven trench
#

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 😭

summer stump
raven trench
#

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

ivory bobcat
#

You need to make a field that's public or serialized with a type that's the script you're wanting to access.

raven trench
#

so i switch out MoneyScript for the actual name of the script right?

ivory bobcat
#

Next using the inspector, drag and drop the other object with the script into the inspector-field.

raven trench
#

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?

ivory bobcat
raven trench
#

i have that part here man

quasi rose
#

money = target controller? 🤔

ivory bobcat
#

Now you should be able to do Money.Money -= 1

raven trench
quasi rose
ivory bobcat
raven trench
quasi rose
raven trench
#

what else would i name the variable representing money if not money

raven trench
quasi rose
#

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.

ivory bobcat
raven trench
#

oh ok ty

quasi rose
#

because for example, you could also do myScript.bankAccount, etc. it's not just money.

raven trench
quasi rose
gray bough
timber tide
#
if(slot.item == null)
{
  slot.item = newItem;
  slot.image = newItem.image;
  slot.text = newItem.text;
}
ivory bobcat
#

Wouldn't that yield NRE?

#

!= null UnityChanHuh

quasi rose
#

it's setting it.

queen adder
#

slot is the one checked though

quasi rose
queen adder
#

if slot is null, slot.item is null too

timber tide
#

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

quasi rose
ivory bobcat
#

Ah, all good now UnityChanThumbsUp

quasi rose
#

i see now

gray bough
timber tide
#

Throw it on a paste site and post it

eternal falconBOT
timber tide
deft stirrup
#

Hello, how does the Raycasting function work in unity?

gray bough
timber tide
#

InventoryManager.cs

summer stump
deft stirrup
#

How i use this?

summer stump
deft stirrup
#

3d

summer stump
deft stirrup
#

Ok

gray bough
#

InventoryManager.cs

wary sable
#

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)

wary sable
ivory bobcat
#

With the old, you could probably do a loop with every possible key etc

wary sable
wintry quarry
# wary sable new

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

wary sable
#

I'll definity give that a go, thank you!

craggy ledge
#

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?

gaunt ice
#

is there transition from jump attack1 to idle (or other state that can go back to idle)?

craggy ledge
#

Oh yeah, now that i think about it every state actually, if you don’t continue the attack or grounded after jump/jump attack

pulsar lodge
#

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

summer stump
# pulsar lodge

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

pulsar lodge
#

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.

summer stump
teal viper
pulsar lodge
#

sorry thats at the top, only sets to Yes when Move is called, then No again at the end of the method

teal viper
pulsar lodge
teal viper
#

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.

pulsar lodge
#

Rofl, well. the collisions work without the coroutine, but

#

my character is moving like 1000 times faster

teal viper
#

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.

pulsar lodge
#

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.)

teal viper
#

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.

pulsar lodge
#

Well, thats what the isWalkable bool method "should" be there for, maybe that is what isn't working properly.

teal viper
#

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

pulsar lodge
#

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.)

teal viper
# pulsar lodge

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.

pulsar lodge
#

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

teal viper
#

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?

tacit flame
#

Im trying to make a 2d Unity Project and i keep getting this Error

#

whats going on

pulsar lodge
#

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

ivory bobcat
teal viper
normal arrow
#

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 ?

distant mesa
#

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.

fringe pollen
#

Show us your code

#

You've most likely gotten the name of the type wrong

warped ibex
#

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.

languid spire
distant mesa
warped ibex
#

ohh thx, it was that notlikethis ...

abstract finch
#

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);```
upbeat gorge
#

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

small nebula
#

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!?

small nebula
rare basin
# small nebula 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...

▶ Play video
gaunt ice
#

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 ...

upbeat gorge
rare basin
#

you need to show code

upbeat gorge
#

ScoreManager one

#

the one which is attacted on all the enemies

rare basin
rare basin
#

your score manager is null @upbeat gorge

#

it is not referenced

olive lintel
#

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?

upbeat gorge
#

!code

eternal falconBOT
upbeat gorge
#
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);
    }
    
}


rare basin
#

as i said, your scoreManager is not referenced

#

in the Score class

upbeat gorge
upbeat gorge
#

its working i just forgot to assign it

#

so what if i want to spawn objects

#

like this find gameobjectswith tag is in start

rare basin
#

what do you want to do?

upbeat gorge
#

i want to spawn GOs

#

gameobj

#

but i used find gameobjwithtag in start

rare basin
#

how is that related?

#

oh, you wanto spawn enemies

#

and add them into the array of enemies?

upbeat gorge
#

yes

rare basin
#

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

rare basin
#

google it

upbeat gorge
#

oh its a thing

rare basin
#

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

abstract finch
#
        {
            _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?
rare basin
#

depends on what are you trying to achieve

abstract finch
#

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

rare basin
#

so you want to modify the currentModifier value based on the animation curve?

abstract finch
#

ye[

#

yep

rare basin
#

well, make a animation curve (obviously)

abstract finch
#

yea but where do you plug in the animation curve?

rare basin
#

are you using this code in an Update

#

or coroutine

abstract finch
#

nope its a coroutine

rare basin
#

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;
    }
abstract finch
#

ohhhh

#

thanks

rare basin
#

just evaluate the curve and use this in the lerp

abstract finch
#

got it thanks

rare basin
#

that works too

abstract finch
#

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

somber wren
#

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

teal viper
somber wren
#

it looks like it worked magically after 200 tries on different line of code and then going back to the beginning

ruby python
gaunt ice
#

or set the transform.right

somber wren
#

its velocity is just its updward direction now, its fine i think

stoic spear
#

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()

topaz mortar
#

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

hoary halo
stoic spear
#

yeah it is

eager elm
#

= new () ... new what? I assume Vector3?

#

ah damn, it actually is valid 😄

fierce shuttle
# eager elm ah damn, it actually is valid 😄

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)

eager elm
#

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

wintry quarry
harsh owl
#

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

rare basin
#

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

hexed terrace
#

This is a code channel, #📱┃mobile is where to ask for help with building for Android, but with actual specific questions

ionic zephyr
#

guys, does somebody know how WaitforSeconds works?

keen dew
#

Yes, lots of people do

ionic zephyr
#

im having trouble using it

#

because it doesnt have any effect on my script

gaunt ice
#

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

eternal falconBOT
keen dew
#

Show your code and explain the issue, that'll help you way more than just asking about them generally

rich adder
ionic zephyr
#

the issue is I want that once an object collisions with my player it inverts controlls (speed is set negative)

near saddle
#

before i start coding a* pathfinder should i create a graph in my game

ionic zephyr
#

but I want it to wait 5 seconds until having the controlls normal again

verbal dome
rich adder
#

IEnumerator VuelveNormal()

ionic zephyr
#

let me check

#

sorry it is in spanish

#

it isnt

rich adder
#

then the coroutine is never started

ionic zephyr
#

sorry, Im a little noob. Is the coroutine the same as a method?

rich adder
#

IEnumerator

ionic zephyr
#

yes I mean theorically the StartCoroutine is like a mention to call a method

rich adder
#

if Line 42 is not printing the coroutine was never started

ionic zephyr
#

so how can i assure it starts?

rich adder
#

make sure the if condition is true?

#

start by debugging your triggerenter

ionic zephyr
#

the condition is fine because the speed turns negative

#

as it says in the condition

verbal dome
ionic zephyr
#

what is a coroutine?

#

sorry for all the questions

rich adder
#

IEnumerator lol

#

in unity

polar acorn
ionic zephyr
rich adder
#

are you sure its active the whole time?

polar acorn
ionic zephyr
#

it is destroyed once it contacts the player

#

oooh

#

i had unable before the Coroutine thing

#

could it be that?

polar acorn
#

If an object is destroyed or disabled, all coroutines currently running on it are canceled

ionic zephyr
#

it still doesnt print the debug

#

therefore it doesnt execute the order

polar acorn
#

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

ionic zephyr
#

the first in the IENumerator?

#

no

queen adder
#

I am trying to assign a material to a 3D object plane but the plane is still transparrent for some reason. Anyone help please?

polar acorn
ionic zephyr
queen adder
polar acorn
ionic zephyr
#

this is wierd. I put the setactive(false) into the coroutine thing and it executes but not the debug

rich adder
#

then you probably have debugs collapsed or somethin

ionic zephyr
#

but it doesnt set the speedvalue to the normal one either

reef anvil
#

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)

polar acorn
rich adder
#

if IInteractable is an interface it shuld be implemented in PlaqueZero

reef anvil
#

yep, thats the issue

#

thank you!

#

very stupid oversight

#

it needs to be there after : MonoBehaviour like it is in the other script 🤦‍♀️

rich adder
#

you can add as many as you need to a class eg public class Foo : MonoBehavioir , IInteractable, ISaveable, IDamagable

reef anvil
#

code works now

ionic zephyr
#

what is this

rich adder
#

it means you added something new to prefab thats not on the original

ionic zephyr
#

oh okay

wintry quarry
rich adder
#

is it? ohh

ionic zephyr
wintry quarry
#

which means you created a new file and haven't committed it to the repository yet

reef anvil
#

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)

rich adder
#

or you added something new to a prefab 🤷‍♂️

wintry quarry
#

oh right

#

you're right

#

I was thiking this was from the project window

rich adder
#

do they use the same icons lol

#

oh wait i think VC is a checkmark

wintry quarry
#

I'm not actually sure because I don't use Unity version control integration

rich adder
#

huh could've sworn they were green 🤷‍♂️ but yeah i dont use it myself I just recall the prefab + icon in 2022 changed

ionic zephyr
#

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

wintry quarry
ionic zephyr
#

okay, let me try, thanks a lot

#

i checked and i dont do that in any part of the code

wintry quarry
#

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

polar acorn
ionic zephyr
#

I already sent it

rich adder
#

this isnt what they asked

#

is this console or unity window?

ionic zephyr
#

visual studio

rich adder
#

then its not what they asked is it?

ionic zephyr
#

oh okay

#

the error there is not the problem

#

ive been having this error there for a while

polar acorn
#

It could be

#

When an error occurs, code stops

#

At the very least it'll make the console cleaner

keen dew
#

You can't know that this script doesn't throw an error because the console is flooded with errors from the other script

hearty gorge
#

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

ionic zephyr
polar acorn
ionic zephyr
#

there isnt any variable in the inspector i can assign

eager elm
summer stump
polar acorn
ionic zephyr
#

it is assigned

polar acorn
# ionic zephyr

Then you have a different instance of the HealthManager script where it is not assigned

summer stump
ionic zephyr
#

yess i found it

#

thanks a lot

hearty gorge
eager elm
hearty gorge
#

gotcha, how best to initialise the list? Just check if its null in my editor before accessing it I guess

wintry quarry
#

i.e. the serializedObject.ApplyModifiedProperties(); bit

#

notably you're doing the SetDirty part before rendering the tiles list

eager elm
hearty gorge
hearty gorge
hearty gorge
eager elm
ionic zephyr
wintry quarry
hearty gorge
#

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

eager elm
hearty gorge
#

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

ionic zephyr
#

oh okay

#

nevermind

summer stump
ionic zephyr
#

yes bro thanks a lot

hearty gorge
ionic zephyr
wintry quarry
hearty gorge
#

Ah cool thanks, ill try going that route

eager elm
ionic zephyr
#

oh really? but then the instant is still there

#

and it lags the hole thing

warped ibex
#

Can anyone tell me why my second slider is not updating the value placed on it? Follow the prints.

summer stump
ionic zephyr
#

isnt the excess of gameobjects a cause of lag?

summer stump
#

Creating and destroying is more costly than enabling disabling usually. To an extent

Which is the justification for pooling

ionic zephyr
#

Oh ok, my god im learning a lot today xdxd

#

thanks again

wintry quarry
#

you shouldn't be reaching deep inside other objects like that

#

and you can't rely on any specific ordering for GetComponentsInChildren

novel shoal
#

@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

summer stump
#

Non-primitive Types is what I said

novel shoal
summer stump
#

And it's a phrase I made up on the spot to just mean anything other than primitive types

summer stump
#

OOP represents a programming architecture. It uses inheritance and abstraction

novel shoal
#

i'll go on with the course and figure out on my own lol

summer stump
summer stump
#

Classes are an example of a TYPE though

novel shoal
#

i thought they were cuz when i did the python tutorial, the guy said "we'll be talking about object-oriented programming"

summer stump
visual delta
#

Why can’t i drag a script into my player prefab

novel shoal
#

a question

#

if "function" are called "methods" in c#, how are the "methods" (the ones followed by the dot) called?

eager elm
eager elm
summer stump
novel shoal
#

okok

#

in python they were called methods so i was confused

summer stump
novel shoal
summer stump
#

I use python too btw. Quite extensively

#

The difference between a method and function is scope

novel shoal
#

lol

#

it's obvious that if i don't study i will be confused

#

my english sucks tho, sry

summer stump
unreal phoenix
#

Not sure how to stop the value boxes from appearing to the side like that. Or how to configure the massive gap

unreal phoenix
#

It's a PropertyField

rich adder
tacit grotto
#

Can a static Rigidbody gain velocity?

summer stump
wintry quarry
#

no

#

This type of Rigidbody2D should never repositioned explicitly. It is designed to never move.

tacit grotto
#

What if I constantly set it's position to another gameobject, which is moving?

summer stump
green copper
#

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

wintry quarry
#

What does RescaleCamera() do?

green copper
#

it's the function that adds letterboxing

dry tendon
#

!code

eternal falconBOT
green copper
#

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

eager elm
#

how do you move the selector arrow?

green copper
#

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

eager elm
green copper
#

no, it's only called when either directional button is presset while paused and with an active menu

harsh owl
#

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

rich adder
#

nice gpt code