#archived-code-general

1 messages · Page 15 of 1

orchid bane
#

.

gaunt garden
#

No matter what kind of trickery you use it will always be slower than not using a task

leaden solstice
#

Yeah

#

Unless you're utilizing thread pool, but you can't do much without Unity API

gaunt garden
#

If you want maximum performance store a unique index for your object inside a dictionary, and use that same index on a nativelist which contains the time for each object. Write a burst compiled IJobFor that increments the time and writes all things that exceed their time to another list, then iterate that on the main thread to destroy your objects

devout solstice
#

Can I have a disabled object in a list?

gaunt garden
#

Of course, disabled is just a property on the object

devout solstice
#

Ok

#

I just know some things you can't do if the object is disabled

somber nacelle
devout solstice
#

true

#

I just thought maybe it wouldn't be able to find it to know if it still existed or something

gaunt garden
#

It's just normal C# code, nothing is going to steal the reference from the list

somber nacelle
gaunt garden
somber nacelle
#

not all of them do, and it's only in 2021+

gaunt garden
#

It's definitely been in longer than that

somber nacelle
#

ah just looked it up again, only FindObjectOfType and FindObjectsOfType have that overload and it's only been in since one of the 2020 versions as far as i can tell.

vague slate
#

Is there anything built-in in Unity for making quest-like graphs?

gaunt garden
gaunt garden
somber nacelle
#

wow TIL that GetComponent is a Find method, and here i was thinking that the Find methods i was referring to literally have the word Find in their name

vague slate
#

I'm considering chain of ScriptableObjects atm

gaunt garden
vague slate
#

but it's not very good for visualizing result

gaunt garden
#

I used it to write an ability system and it worked pretty well

dark torrent
#

is there a stack panel for creating clean menus?

gaunt garden
#

@vague slate it's the same one used to create the shader graph editor if you've used that, so it would look similar to that

gaunt garden
somber nacelle
#

because i initially specified that the Find methods wouldn't find it if disabled, so you countered with "bUT gEtCoMpONenT"

gaunt garden
#

Those are the only two "Find" methods...

somber nacelle
#

the "Find" methods I was referring to all have "Find" in their name, like FindWithTag, Find, FindObjectOfType, etc. I was not referring to GetComponent because GetComponent can already get a disabled component, it is only GetComponentInChildren/Parent that wouldn't be able to without that overload and those overloads are still fairly new anyway

placid hearth
#

Anyone else spend 5 minutes trying to figure out why something isn’t working only to realize you for a capital letter somewhere

somber nacelle
#

sounds like your IDE is probably not configured, unless your issue is that you are relying too heavily on strings being equal

placid hearth
somber nacelle
#

#854851968446365696 has a guide for configuring your IDE (assuming that is what you are referring to)

placid hearth
gaunt garden
#

Well yes, I was referring to why it broke

#

e.g. a string comparison or something

placid hearth
somber nacelle
placid hearth
gaunt garden
placid hearth
#

Ok

gaunt garden
#

(I was joking)

lyric forge
#

I'm working on a game where you play as a ghost who can control various robots. Right now I'm trying to figure out how to enable and disable the robot's ability to move when you're possessing it. Each robot would have different abilities and therefore likely different scripts to handle them.

#

I currently have the possession set so that the ghost is made a child of the robot and hidden

gaunt garden
#

Create a script for each "ability" with a common interface and call the required methods for each ability on the robot that was possessed?

lyric forge
#

I've heard someone use that term before, interface. I don't really know what it is though

gaunt garden
#

In the common language it would mean the interaction point between two systems, in this case your ghost and robot abilities

#

You could have something along the lines of an interface IRobotAbility that implements a ExecuteAbility function, then find all components implementing that interface on the robot and call them

#

The specifics would depend on your game

lyric forge
#

I wouldn't want the robots to have the same abilities the ghost does though. For example, they have different movement. The ghost can move around freely and the robot is restrained to the ground.

gaunt garden
#

On a higher level view the "player" is just possessing the ghost, so there isn't really a huge difference. At the end of the day you are probably sending your inputs to an object and then doing something based on those inputs

#

Whether that's a ghost or robot doesn't really matter

gaunt garden
#

So the ghost could have a GhostMovementAbility, and the robot could have a RobotMovementAbility and a ShootRocketsAbility, with all three of thoses implementing some common interface

lyric forge
#

If it's not too much, could you expand on the movementability bit? What might GhostMovementAbility look like?

gaunt garden
#

It depends on what the contract would be. In the simplest form the object ability would handle everything itself, but that could lead to some code duplication. I can write you an example for that if you want

lyric forge
#

That would be ideal. I learn best with examples

#

I currently have ghost movement like this

void Update()
    {
        //This code gets the direction inputted by the player and applies a force multiplied by it.
        moveDirection = inputActions.Ghost.Move.ReadValue<Vector2>();
        rb.velocity = speed * moveDirection;
    }```
gaunt garden
#
public class Ghost : MonoBehaviour{ }

public interface IAbility
{
    public void StartPossession(Ghost ghost);
    public void EndPossession();
    public void SomeCustomAction();
}

public class GhostMovementAbility : MonoBehaviour, IAbility
{
    //Set everything related to the ability up here
    public void StartPossession(Ghost ghost) { }

    //Clean up ability usage here
    public void EndPossession() { }

    //Do something else here
    public void SomeCustomAction() { }
}

This would be an example with interfaces. If your abilities are very simple you could even skip the interface part and just enable / disable the components when the object is possessed and let the unity event functions handle your logic

#

e.g. OnEnable would register callbacks for input, OnDisable would clean up, and Update would handle your per-frame logic

lyric forge
gaunt garden
#

Like I said, I can only give vague recommendations since I don't know what your project looks like, but I would do it like this:

Have some kind of GhostPossessionController that handles possession of objects, and when the game starts, "possess" the ghost. This would set up input handling for your GhostMovementAbility by calling StartPossession on it, and if you move to a robot and possess it, it would call EndPossession on the GhostMovementAbility, deregistering input handling, and call StartPossession on your RobotMovementAbility to register inputs for that movement

lyric forge
#

Sorry, you lost me.

#

Wait I reread it

#

I think I maybe understand.

#

Would the controller be an empty object?

gaunt garden
#

It can be whatever you want it to be, a component on the ghost might make the most sense

lyric forge
#

Thanks. I think I get it.

gaunt garden
#

Then it could just call GetComponents<IAbility>().ForEach(x => x.StartPossession()) on game start

lyric forge
#

Now I'm confused

#

What does that do

gaunt garden
#

When the game starts, "possess" the object by calling the StartPossession function on all components that implement the IAbility interface on that object

lyric forge
#

Wouldn't that possess every object, not just the ghost?

gaunt garden
#

No, it's using GetComponents, which gets the components on the gameobject on which the script is

lyric forge
#

Oh

gaunt garden
#

Like I mentioned, you can also skip the interface methods and just use the unity event methods if you like, if that is easier to understand

#

To possess and object you would enable all components that implement the interface, and when you stop possessing, you disable those components

#

Then use the unity event methods (OnEnable, OnDisable, Update) to handle your logic

robust spire
#

Wondering if anyone can help me understand a Vector3.Slerp issue. I'm trying to smooth the rotation of a controllers right thumbstick input with the below, but when the Z rotation tries to move from say 1 to -1 (moving clockwise), it bugs out. Similarly, it'll bug out when trying to go below -90 (moving counter clockwise)

if (x != 0f && y != 0f) {
     Vector3 currentRotation = new Vector3(0f, 0f, _weaponPivot.localEulerAngles.z);
     Vector3 targetRotation = new Vector3(0f, 0f, Mathf.Atan2(x, y) * -180 / Mathf.PI + 90f);
     _weaponPivot.localEulerAngles = Vector3.Lerp(currentRotation, targetRotation, ReturnTime * Time.deltaTime);
}
worthy willow
#

For some reason, I am suddenly unable to to open my "PlayerController" script from the Unity Editor. The script still works but I am unable to edit/open it. I am able to open any other script I have made tho..

worthy willow
tame urchin
#

Does anyone know how to check if a GridBrushBase brush is the currently active brush used by the tilemap editor?

clever mulch
#

Or reload all

shrewd obsidian
#

Some shader that is only used at runtime seems to not be included when I build the game and is causing errors, how do I ensure a certain shader is included in a build?

thin hollow
#

Have anybody dabbled in XML serialization? I have these classes:

 public class ConversationEntry
    {
        [XmlAttribute("id")]
        public string id = string.Empty;
        [XmlArray("phrases")][XmlArrayItem("entry")]
        public List<TextEntry> phrases = new List<TextEntry>();
    }
    
    public class TextEntry
    {
        [XmlAttribute("id")]
        public string id = string.Empty;
        [XmlText]
        public string entry = string.Empty;
    }

    [XmlRoot(ElementName = "language")]
    public class LanguageDB
    {        
        [XmlArray("conversations")][XmlArrayItem("conversation")]
        public List<ConversationEntry> dialogues = new List<ConversationEntry>();
    }
        

which requires and produces following xml:

<language>
 <conversations>
    <conversation id="generic">
      <phrases>
        <entry id="con_answer_yes">Yes</entry>
        <entry id="con_answer_no">No</entry>
      </phrases>
    </conversation>
  </conversations>
</language>

Can anybody say what I need to change to get rid of the "<phrases>" tags? I can't seem to make it work without them.

left abyss
#

Hi guys ! I have a question about Particle System in UI. For exemple i have an Mask on a gameobject and a child Particle System on it. But the Mask doesnt apply on the particle system 😭

vocal merlin
thin hollow
# vocal merlin You want to remove <phrases> or the id tag?

I want to remove <phrases>. I tried

 public class ConversationEntry
    {
        [XmlAttribute("id")]
        public string id = string.Empty;
        [XmlArrayItem("entry")]
        public List<TextEntry> phrases = new List<TextEntry>();
    }

but then it just won't load any data at all. - it creates the ConversationEntry, but phrases is empty.

vocal merlin
thin hollow
vocal merlin
#

And just leave in the [XmlArrayItem("entry"]

vocal merlin
#

I don't have dev env to hand, I don't think it will work

#

Oh hah yes, you tried it 😛

#

conversation has become the array

vocal merlin
thin hollow
#

It is a file to hold the text for the dialogue trees in my game, so there will be variable amount of both <conversation> and <entry> inside of each <conversation>.
In reality XML has other sections for other kinds of texts too, but they're working perfectly well so I've omitted them. There's a few articles that talk about xml serialization in Unity on the net, but all of them use pretty "shallow" XML depth, and none tried to do this "array of arrays" thing.

elfin vessel
#

How do I figure out how much physics force is needed to push an object from one point to another?

elfin vessel
#

unfortunately, yes

gaunt garden
#

I think it's possible but probably not easy since you'll also need to account for gravity, mass, drag, friction, etc

#

I think you'll get an ok guess at best

elfin vessel
#

i dont need it to be super accurate, just passable. I have access to gravity and mass

vocal merlin
# thin hollow It is a file to hold the text for the dialogue trees in my game, so there will b...
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="entry")]
    public class Entry {
        [XmlAttribute(AttributeName="id")]
        public string Id { get; set; }
        [XmlText]
        public string Text { get; set; }
    }

    [XmlRoot(ElementName="conversation")]
    public class Conversation {
        [XmlElement(ElementName="entry")]
        public List<Entry> Entry { get; set; }
        [XmlAttribute(AttributeName="id")]
        public string Id { get; set; }
    }

    [XmlRoot(ElementName="conversations")]
    public class Conversations {
        [XmlElement(ElementName="conversation")]
        public Conversation Conversation { get; set; }
    }

    [XmlRoot(ElementName="language")]
    public class Language {
        [XmlElement(ElementName="conversations")]
        public Conversations Conversations { get; set; }
    }

}```
#

Not sure how to do the pretty formatting in discord :/

thin hollow
#

three `

vocal merlin
#

Meh, I'll go read up 😛

vocal merlin
thin hollow
autumn cipher
#

I kinda still need help on this if anyone's willing to

orchid bane
#

How do colliders know if other colliders are nearby?

#

It would be expensive to simply iterate over all the colliders

vocal merlin
autumn cipher
mild wolf
#

does anyone know how I can make it so the player sticks to the platform when the platform is a rigidbody dynamic?

orchid bane
#

I mean I heard they start to eat up way more performance if they are NEAR another collider

#

Is it because these methods are simply way cheaper than an actual collision?

proper oyster
vocal merlin
vocal merlin
autumn cipher
#
if (Physics.Raycast(TR.position, TR.forward, out RaycastHit hit, float.MaxValue, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Collide))
        {
            if (hit.collider.CompareTag("Hitbox"))
            {
                Debug.Log($"hit the hitbox, {hit.distance} meters away");
                IDamagable DamagableObject = hit.transform.GetComponentInParent<IDamagable>();
                uint damage = 0;

                for (byte i = (byte)(WepData.DamageDropOffDistances.Length - 1); i >= 0; i--)
                {
                    if (i == 0 && hit.distance <= WepData.DamageDropOffDistances[i])
                    {
                        damage = WepData.Damage[i];
                        break;
                    }
                    else if (hit.distance > WepData.DamageDropOffDistances[i - 1] && hit.distance <= WepData.DamageDropOffDistances[i])
                    {
                        damage = WepData.Damage[i];
                    }
                }
                DamagableObject.doDamage(damage, DamagableObject, player);
            }
        }```
#

the else if block gives "index out of range" error

vocal merlin
#

You're decrementing your i value, so when you get to 0 the if else statement damage drop off will be -1

autumn cipher
#

oh you're saying it still gets decremented anyways?

vocal merlin
#

You need an or statement in the first if ||

#

If you want it to always go into the first if statement when it reaches 0

#

Otherwise it will take into consideration the hit.distance <= WepData.... and evaluate to continue to where you don't want it to go

proper oyster
#

= 0 means that the last run will be if i is 0

#

i > 0 wild make the last one be index 1

vocal merlin
#

But then he will never get his max damage

proper oyster
#

or clamp the value in
[i - 1]
so that is never below 0

vocal merlin
# autumn cipher but I'm breaking the loop when i reachs 0
List<int> damage = new List<int> { 36, 23, 15 };
List<int> damDropOff = new List<int> { 10, 20, 30 };

int distance = 5;

// Assume max damage
int damageTaken = damage[0];

for (int i = 0; i < damDropOff.Count; i++)
{
    // While the distance is greater than the drop off
    if (distance >= damDropOff[i])
    {
        // Change the damage value
        damageTaken = damage[i];
    }
}```
autumn cipher
#

I'm reading thanks

autumn cipher
vocal merlin
autumn cipher
# vocal merlin show the reworked code
                uint damage = WepData.Damage[0];

                for (int i = 0; i < WepData.DamageDropOffDistances.Length; i++)
                {
                    // While the distance is greater than the drop off
                    if (hit.distance >= WepData.DamageDropOffDistances[i])
                    {
                        // Change the damage value
                        damage = WepData.Damage[i];
                    }
                }```
vocal merlin
pale summit
#

Hi. I've got some issue on my UNITY XR TOOLKIT VR PROJECT. Is it possible to separate the button for the xr director interactor to the xr ray interactor please ?

autumn cipher
pale summit
vocal merlin
autumn cipher
#

after 10 meters the damage should be lowered to 33

#

guess I gotta use clamp like the other friend mentioned

vocal merlin
#

Your data is wrong

#

I see what you want, you want the damage between 10 and 20 = 33 and the damage between 20 and 30 = 30

autumn cipher
#

yeah

autumn cipher
clever spade
vocal merlin
#

Yes they are Galtz, you can see them just above

clever spade
#

maybe I'm looking at the wrong one?

autumn cipher
autumn cipher
autumn cipher
clever spade
#

Oh I see it now,

                   {
                       damage = WepData.Damage[i];
                   }```
i - 1 is less than 0
autumn cipher
#

@vocal merlin hold on I made a huge mistake

#

if I have x number of damage values, I should have x-1 number of damage drop off ranges

#

thank you for your determined helps

#

I'm normally not this stupid lol it's 5 am here

plucky karma
#

sleep people... Your brain cannot function if you're sleep deprived.

autumn cipher
#
        for (byte i = 0; i < WepData.DamageDropOffDistances.Length; i++)
                {
                    if (i == 0)
                        continue;
                    else if (i == WepData.DamageDropOffDistances.Length - 1 && hit.distance >= WepData.DamageDropOffDistances[i])
                    {
                        Debug.Log("FIRST else if i : " + i);
                        damage = WepData.Damage[i+1];
                        break;
                    }

                    else if (hit.distance > WepData.DamageDropOffDistances[i - 1] && hit.distance <= WepData.DamageDropOffDistances[i])
                    {
                        Debug.Log("SECOND else if i : " + i);
                        damage = WepData.Damage[i];
                    }
                }
``` it's such a spaghetti but it works!
whole shore
#

So I’m making a game, but I can’t find any code I’m looking for. Basically I wanna make it so when they run into a box collider and press “E” it switches them to a new scene, but i can’t find a script or any YT videos to help

whole shore
full scaffold
whole shore
#

Okay thank you

pine flume
#

Is there a way to get a sprite by index on a sliced sprite?

leaden solstice
dark torrent
#

what class is a scene? I am trying to add a serialized field so that I can assign a scene from the inspector.. not sure if this is possible.

vivid wind
#

I have a List of CustomClass. CustomClass contains a DateTime which I check against the GameTime to see if it is expired. When it is expired I remove it from the list in a Update method of a Mono. When the class is removed from the list and Update Finishes, does that instance of CustomClass get cleaned up?

#

Think I found my answer. Since I'm using C#, once the class is unreachable it should get scooped by the Garbage Collector.

warm wren
soft shard
oblique spoke
dark torrent
#

i was trying to add scenes without hard coding them.. I could add them to the inspector and then reference them easier in code

buoyant crane
#

either make a public int representing the build index, or if you prefer you can also reference scenes by string

dark torrent
#

@buoyant crane so, adding them to the Build Settings, then reference them by their number?

buoyant crane
#

yep that’ll work

dark torrent
#

thanks!

dark torrent
#

okay... dumb question...

#

can you have 2 scenes loaded at the same time?

#

for instance... i have my game running and I click the settings button... can I have the settings window scene pop up on top of the game scene?

#

or should that be a prefab?

full scaffold
dark torrent
#

so, if I want the same settings window.. i need to add the this canvas to each scene?

clever spade
#

ideally you want your settings saved externally somewhere, otherwise it would be rather annoying to redo your settings every time you play the game or even worse, when you load a scene

soft shard
# dark torrent so, if I want the same settings window.. i need to add the this canvas to each s...

You could have your settings canvas as a prefab, spawn it once then toggle it as needed throughout your games lifecycle, that can be done as a "singleton" if you prefer - I usually make a "init" scene as my index 0, that spawns the prefab, audio pools and anything else that should persist, and then toggle them in the relevant scenes/button events that need them, though there are many ways to skin a cat

dark torrent
#

@soft shard that is what I am trying to do... create a "GameController" that has all of my scenes declared and stores all of my essential variables

soft shard
junior aurora
#

I have been trying to find a way to split a sprite in half during runtime and I have had no success. I want to avoid having to create a 3 sprites by hand(1 full item, other 2 being the halfs to make a whole).

Anyone know any resource for it? or how I can do it?

clever spade
#

If half is the only thing you need then why not duplicate the sprite and use a sprite mask to hide half of the sprite?

ornate idol
#

Does anyone know a way to create a moveable inverse mask? I want to have a shadow overlay with a diamond cut out focused on an object the user selects as a highlight. Example in image. I was thinking of just grabbing the position of the selected object and setting that to the world position of the diamond which is used as an inverse mask on the translucent background , but that moves the shadow which is its child. Is there any better solution than inverting the change in position?

junior aurora
#

not a bad idea. I'll look more into it.

devout wigeon
#

I'm trying to figure out how to properly reference namespaces for assets that I'm using in a little toolbox package that I'm making for personal convenience.

For example, I'm using I2 Localize as part of my custom Text component prefab. I was able to reference TMPro's assembly definition in the Assembly Definition Asset for my package, but I2 and other assets doesn't seem to have one.

I'm also not sure how to reference assets as dependencies in the package.json file because I don't see a "com.x.y" name for them anywhere. I appreciate any assistance!

quartz folio
#

You would need to create assembly definitions for anything that doesn't have them

#

and you cannot reference asset store assets as dependencies, because they aren't a part of the package ecosystem

devout wigeon
#

Okay, that's somewhat disappointing. Is there an alternate approach that makes more sense? Other than cloning the toolkit repo into the assets folder independently? Also, thank you for your answer!

tropic sleet
# devout wigeon Okay, that's somewhat disappointing. Is there an alternate approach that makes m...

It depends on how hacky you want to get. You could store the asset store toolkit in your own private git repo, then make it a submodule of your package and give access to whoever needs it manually. Or you could turn the dependency into a package and define the package location as somewhere in your hard drive, then use the same reference path for every project. You could try to make a script that downloads / updates the dependencies from the asset store "manually" as soon as you load the package. Or you could just include the asset store assets in your package and update them every once in a while. (Just some ideas)

In general, asset store assets don't work great as dependencies of packages. It's better to see packages as you would programs on your computer and asset store assets as files in your project. How tightly you want to couple your package to those assets is up to you, but I would recommend having as few external dependencies as possible.

devout wigeon
grizzled needle
#

hello! if I create a private struct and then provide a property that points to it, would the values inside of the struct be open to change from outside classes?

#

here's the code example

#
{
  public float value;
}

public class ClassOne
{
  private ExampleStruct _alpha;
  public ExampleStruct Alpha => _alpha;
}

public class ClassTwo
{
  ClassOne testClass;

  void ExampleFunction()
  {
    testClass.Alpha.value = 100f;
  }
}
#

is this possible?

#

Okay, i just tested it and it is not possible, that's great!

hexed pecan
#

Accessing a struct gives you a copy of it, so you would have to assign it back to apply any changes

plain yacht
#

@grizzled needle Are you sure the reason it doesn't work isn't just that you never initialize testClass inside ClassTwo?

grizzled needle
#

For my case, I need it to be protected! I remembered that structs couldnt be changed that way, but I wanted to make sure.

grizzled needle
plain yacht
grizzled needle
#

Thanks for sending me that link! But having ClassOne restrict it was my intention! Its not meant to be a readonly struct lol, I was just asking the question as a confirmation of what I was intending, just clearing my doubts lol

polar sail
#

hey guys,i have a mesh with a scale of 20,20,20 but when i log it out it's completely different

#

why is that?

plain yacht
#

I think you need to elaborate a bit more if we're supposed to understand.

polar sail
#

i have an object placed in the world that has a scale of 20,20,20(i've set that in the editor)

#

and i'm casting a raycast on it

#

and when i log out it's localScale it returns a completely different vector

soft shard
# polar sail and i'm casting a raycast on it

Are you certain the .collider your cast hit is the object in question? For example if you logged Debug.Log(hit.collider, hit.collider); then selected the log from the console, does it ping the correct object you expect? (the second param of Debug.Log will highlight any object passed to it, either in the Hierarchy if it exists there, or the Project view, if it exists there instead)

wind wraith
#

when a player holds down a vertical and a horizontal input at the same time, they move twice as fast. is there any simple and clean way of stopping this?
i would usually half the speed of the player if both the vertical and horizontal inputs are received but that wouldnt work for my current project as controller input is also used, meaning the value can be anywhere between 0 and 1. not only that but i feel like theres a better way of doing it for future projects anyway.

simple egret
wind wraith
tight isle
#

So i have this equation in my code and I am very confused. It works, but how is a quaternion being multiplied by a vector, and returns a vector?

Vector3 target = Quaternion.Euler(center_point.rotation.eulerAngles) * new Vector3(Mathf.Cos(angle_jr) * Mathf.Cos(angle_ir), Mathf.Sin(angle_ir), Mathf.Sin(angle_jr) * Mathf.Cos(angle_ir)) + center_point.position;
simple egret
tight isle
simple egret
#

Hard to say, you didn't mention what the formula is supposed to do.
Let's take an example instead, Vector3.forward, multiplied by your rotation would yield transform.forward

#

And the last version of the code you posted shows multiplication of two Quaternion values, which internally just "adds" the two rotations.

tight isle
#

Does the last version do the same thing as first? Since im just wondering how the multiplication of vec by quat works.

simple egret
#

Here it would be the same as multiplying a vector, you would assign it to something else though.
Vector * Quaternion returns Vector, so you would assign it to EulerAngles
Quaternion * Quaternion returns Quaternion, so you would assign it to transform.rotation

tight isle
#

aight great.

#

thanks

mental rover
fierce granite
#

why does the enemy still take hp when he is dead?

#

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;

public class PLayerController : MonoBehaviour
{
NavMeshAgent agent;
Animator anim;
public int health = 100;
public Text healthText;

// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
    agent = GetComponent<NavMeshAgent>();
    anim = GetComponent<Animator>();
    healthText.text = "Health:" + health.ToString();
}

// Update is called once per frame
void Update()
{
    Move();
}
private void Move()
{
    float moveZ = Input.GetAxisRaw("Vertical"); 
    float moveX = Input.GetAxisRaw("Horizontal"); 

    

    Vector3 position = transform.position;
    Vector3 move = (transform.right * moveX + transform.forward * moveZ) * agent.speed;

    agent.destination = position + move;

    if(moveX !=0 || moveZ != 0)anim.SetBool("Run", true);
    else anim.SetBool("Run", false);
}
public void Damage(int dmg)
{
    health = health - dmg; //health -= dmg;
    UpdateHealthUI();
    healthText.text = "Health:" + health.ToString();
    if (health <= 0)
    {
        GetComponent<GameManager>().playerLive = false;
        Debug.Log("You're dead.");
    }
}
void AddHealth(int hp)
{
    health += hp;
    UpdateHealthUI();
}
private void OnTriggerEnter(Collider other)
{
    if (other.tag == "Medic")
    {
        Destroy(other.gameObject);
        AddHealth(25);
    }
    else if (other.tag == "Ammo")
    {
        Destroy(other.gameObject);
        GetComponent<WeaponScript>().AddAmmo(25);
    }
}`
#

that is player controller

vivid furnace
#

quick question, im trying to import a package into unity from git using the package manager but it keeps throwing this error anyone know what its about?

fierce granite
#

thx

slim spruce
#

hi.
i've got some mouse look code for my playercontroller, but can't really figure out how to clamp the Y axis-(looking left, and looking right) for the life of me. i've managed to do it for the X axis so you can't flip the camera, but no luck for the Y. i'm basically just really confused about what variable i'm actually supposed to clamp here, or how to go on about this proper.
thank you!

    [Header("Vision Variables")]
    [SerializeField] float mouseSensitivty = 3.5f; 
    [SerializeField][Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
    [SerializeField][Range(0.0f, 0.3f)] float mouseSmoothTime = 0.025f;
    [SerializeField][Range(0.0f, 90.0f)] float upperLookLimit = 90f;
    [SerializeField][Range(0.0f, 90.0f)] float lowerLookLimit = 90f; 
    //[SerializeField][Range(0.0f, 90.0f)] float leftLookLimit = 90f;                  // these two are what i'm trying to implement
    // [SerializeField][Range(0.0f, 90.0f)] float rightLookLimit = 90f; 
    float cameraAxisX = 0.0f; 
    Vector2 currentMouseDelta = Vector2.zero;
    Vector2 currentMouseDeltaVelocity = Vector2.zero;

    void UpdateMouseLook(){
        Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);
        cameraAxisX -= currentMouseDelta.y * mouseSensitivty;
        cameraAxisX = Mathf.Clamp(cameraAxisX, -upperLookLimit, lowerLookLimit);
        playerCamera.transform.localEulerAngles = Vector3.right * cameraAxisX;
        transform.Rotate(Vector3.up * currentMouseDelta.x * mouseSensitivty); // this is the line that deals with Y axis rotation
 }```
long barn
#

I'm getting the Error: ArgumentException: An item with the same key has already been added. Key: 5 ```cs
public class FileGenerator2 : EditorWindow
{
...

void SetTreeView()
{
    var treeView = rootVisualElement.Q<TreeView>();

    Category categories = DebugCategory();

    int id = 0;
    TreeViewItemData<Category> treeRoot = categories.ConvertWithChildren(ref id);

    treeView.SetRootItems(new List<TreeViewItemData<Category>>() { treeRoot });     <------ Error

    treeView.makeItem = () => new Label();

    treeView.bindItem = (VisualElement element, int index) => (element as Label).text = treeView.GetItemDataForIndex<Category>(index).Name;
}

Category DebugCategory()
{
    Category debugCategory = new Category("Base", children: new List<Category>()
    {
        new Category("1"),
        new Category("2"),
        new Category("3"),
        new Category("4"),
        new Category("5")
    });

    return debugCategory;
}

}

public class Category
{
public string Name { get; private set; }
public List<Category> Children { get; private set; }

public void AddChild(Category category)
{
    Children.Add(category);
}

public TreeViewItemData<Category> ConvertWithChildren(ref int id)
{
    Debug.Log(id);
    List<TreeViewItemData<Category>> children = new List<TreeViewItemData<Category>>();

    for (int i = 0; i < Children.Count; i++)
    {
        id += 1;
        children.Add(Children[i].ConvertWithChildren(ref id));
    }

    TreeViewItemData<Category> itemData = new TreeViewItemData<Category>(id, this, children);

    return itemData;
}

public Category(string name)
{
    Name = name;
    Children = new List<Category>();
}

public Category(string name, List<Category> children)
{
    Name = name;
    Children = children ?? new List<Category>();
}

}

#

I've tried printing "id" in cs Category.ConvertWithChildren() but thats seamed fine to me. I've also googled around a bit but didnt get any other ideas what the issue might be if "id" doesnt have any doubled logs.

scarlet bane
#

When i set my joystick to inactive and the active again the joystick doesnt reset, and the joystick is stuck in a direction until another direction is inputted.
How would i go about resetting the joystick direction?

autumn cipher
# slim spruce hi. i've got some mouse look code for my playercontroller, but can't really fig...

I recommend setting transform's rotation directly rather than using Rotate()
Here's how I do my FPS mouseLook, good luck

    public Transform TR;
    public Vector2 Sensitivity = new Vector2(30f, 30f);
    const byte SENS_M = 50; // SENS_M is optional, only to adjust the sensitivity
    [HideInInspector] public Vector2 Rot;

    private void Awake()
    {
        TR = transform;
    }
    public void Update()
    {
        Rot.x -= GetAxisRaw("Mouse Y") * Sensitivity.x / SENS_M;
        Rot.y += GetAxisRaw("Mouse X") * Sensitivity.y / SENS_M;


        // Clamp the X Y rotations
        if (Rot.x < -90f) 
        Rot.x = -90f; 
        else if (Rot.x > 90f) 
        Rot.x = 90f;
        if (Rot.y >= 360f || Rot.y <= -360f) 
        Rot.y = 0f;

        TR.rotation = Quaternion.Euler(Rot.x, Rot.y, 0f); // Rotates the camera
slim spruce
fierce granite
autumn cipher
#

I'm trying to sort an RaycastHit[] based on their distances from PhysicsRayCastNonAlloc(), any non LINQ sources that can help?

swift falcon
#
 shoulder.localRotation = Quaternion.RotateTowards(shoulder.localRotation, Quaternion.Euler(poseData.shoulder), 10f);

sometimes it picks wrong way cuz its closer. basically it can achieve a target rotation by either rotating backward or forward. and sometimes, depending on positions, it choses undesired direction.
what can I do here?

unborn fern
#

transparent in editor but not in play mode?

#

nvm i fixed it

slim spruce
# slim spruce hi. i've got some mouse look code for my playercontroller, but can't really fig...

i fixed it!
still don't really understand why it works but hey, i'm happy. also made the cameraAxis into a vec2; would be cool to get the same declaration but couldn't get it to work when i tried it, cause of update or something

    [Header("Vision Variables")]
    [SerializeField] float mouseSensitivty = 3.5f; 
    [SerializeField][Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
    [SerializeField][Range(0.0f, 0.3f)] float mouseSmoothTime = 0.025f;
    [SerializeField][Range(0.0f, 90.0f)] public static float upperLookLimit = 90f;
    [SerializeField][Range(0.0f, 90.0f)] public static float lowerLookLimit = 90f; 
    [SerializeField][Range(0.0f, 90.0f)] public static float leftLookLimit = 90f; 
    [SerializeField][Range(0.0f, 90.0f)] public static float rightLookLimit = 90f; 
    Vector2 cameraAxis; // both x and y
    Vector2 currentMouseDelta = Vector2.zero;
    Vector2 currentMouseDeltaVelocity = Vector2.zero;

    void UpdateMouseLook(){
        // gets our X and Y axis - M
        Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
        // mouse smoothing - M
        currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);
        
        // apply mouse sens //possibly get this down into one line if i was smart enough
        cameraAxis.x -= currentMouseDelta.y * mouseSensitivty;
        cameraAxis.y += currentMouseDelta.x * mouseSensitivty;

        // makes sure we can't do a first person front/backflip - M
        cameraAxis.x = Mathf.Clamp(cameraAxis.x, -upperLookLimit, lowerLookLimit);
        cameraAxis.y = Mathf.Clamp(cameraAxis.y, -leftLookLimit, rightLookLimit);
        
        // looking up and down
        playerCamera.transform.localEulerAngles = Vector3.right * cameraAxis.x;
        
        // lets us move left and right + applies the clamped axis
        transform.eulerAngles = new Vector3(0, cameraAxis.y, 0);
    }
autumn cipher
fiery crest
#

This is a car script if anyone needs one using UnityEngine;

public class CarController : MonoBehaviour
{
public float speed = 10f;
public float turnSpeed = 5f;
public WheelCollider frontLeftWheel, frontRightWheel;
public WheelCollider rearLeftWheel, rearRightWheel;
public Transform frontLeftTransform, frontRightTransform;
public Transform rearLeftTransform, rearRightTransform;

private void Update()
{
    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");

    frontLeftWheel.steerAngle = horizontal * turnSpeed;
    frontRightWheel.steerAngle = horizontal * turnSpeed;

    rearLeftWheel.motorTorque = vertical * speed;
    rearRightWheel.motorTorque = vertical * speed;

    UpdateWheelPoses();
}

private void UpdateWheelPoses()
{
    UpdateWheelPose(frontLeftWheel, frontLeftTransform);
    UpdateWheelPose(frontRightWheel, frontRightTransform);
    UpdateWheelPose(rearLeftWheel, rearLeftTransform);
    UpdateWheelPose(rearRightWheel, rearRightTransform);
}

private void UpdateWheelPose(WheelCollider collider, Transform transform)
{
    Vector3 position;
    Quaternion rotation;
    collider.GetWorldPose(out position, out rotation);
    transform.position = position;
    transform.rotation = rotation;
}

}

wind wraith
#

im setting up a script that i can put on objects that can be interacted with by the player. this script will be on a bunch of different prefabs that will do different things when interacted with. how would i do this?
my idea is for there to be 2 scripts on the object, the interaction script and the script specific to the object. when the object is interacted with (this is handled by the interaction script) it would run a function in the other script. however im not sure how to access the other script from the interaction one because the script would be different on each different prefab

proper oyster
wind wraith
wraith vector
#

I was following a tutorial and reach this stage:
PlayGamesPlatform.Instance.SavedGame.OpenWithAutomaticConflictResolution("MyFileName", DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, SaveGameOpen);
But when I check

{
if(status == SavedGameRequestStatus.Success)
        { 
          ...
        }
        else
        {
            Debug.Log("not working?");
            Debug.Log(status);
        }
}```
status is : "InternalError"

Any idea why?
plain yacht
#

@wraith vector Not unless you post the error itself.

toxic notch
#

I'm trying to get poolable objects working. I'm instantiating the poolable objects in the object pool class. Then under the poolableobject I have a property called ObjectPool Parent which is a reference back to the pool so it can be added back in. The problem I'm running into is that on instantiation when I do
poolableObject.Parent = this;
and then look in the inspector there is no parent set under the field. Any ideas?
https://gist.github.com/maximusthegreatest/a78895459dbe2f8fc59a5aabe3162387

Gist

GitHub Gist: instantly share code, notes, and snippets.

wraith vector
kindred wyvern
#

If i have 4 different prefabs of a room and i got a script for these rooms to spawn on random locations. Is it possible for a spawnmanager of somekind to spawn in a random amount of enemies in each room?

Whats the best practise? Have an empty game object named "spawner" in each prefab-room, and instantiate on a random location on that object, any tips of how i should approach this :D?

wraith vector
modern creek
# kindred wyvern If i have 4 different prefabs of a room and i got a script for these rooms to sp...

Lots of different ways to do this, each with pros/cons, but until you're familiar with all of them, it's probably best to just experiment and see what works for you. Here's some approaches:

  1. Create a DDOL (DontDestroyOnLoad) spawn manager singleton with static methods to spawn a room.
  2. Let rooms spawn themselves - create one actual object in the room with links to the prefabs, tell that "parent" object to spawn a room. It selects a prefab (randomly or otherwise) and spawns it.
  3. Embed the logic for spawning directly in whatever is building the scene. Randomly select from the available prefabs and have it select, configure, instantiate and spawn them.
kindred wyvern
tired egret
potent sleet
#

this again, did you google it

potent sleet
tired egret
#

let me try that

forest patrol
#
            .Where(subClass => subClass.IsClass && !subClass.IsAbstract && subClass.IsSubclassOf(type));``` will this work on Android or ios ?
potent sleet
tired egret
leaden solstice
#

Works for non-stripped types

tired egret
#

first time for me to physically touch a dll

potent sleet
#

touch it gently

autumn cipher
#
        RaycastHit[] hits = new RaycastHit[10];
        int numberOfHits = Physics.RaycastNonAlloc(TR.position, TR.forward, hits, float.MaxValue, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Collide);
        RaycastHit[] sortedHits = hits;
        for (int t = 0; t < numberOfHits; t++)
        {
            if (t == numberOfHits - 1 && hits[t].distance > hits[t - 1].distance)
            {
                //do something here, idk
                break;
            }
            else if (hits[t].distance < hits[t + 1].distance)
            {
                sortedHits[t] = hits[t];
            }


            Debug.Log($"hit the object, {sortedHits[t].distance} meters away");
        }
``` still trying to sort these hits from closest to furthest
#

I can't believe I'm failing to make a typical sorting algorithm

soft shard
lucid valley
#

if you call it often, might as well avoid the GC for that array

#

the sorted array will still cost unless you reuse that too

autumn cipher
lucid valley
#

no they are not

#

at least that is my understanding of it if they are object types (arrays of anything are objects) so are managed memory

lyric forge
#

How could I make it so an object can only be pushed by a certain type object, and not others?

#

Say you have 2 objects you can control. I want to make a gameobject that can be pushed around by object 1, but can't be moved by object 2.\

#

Also I'm working on a puzzle game which takes the form kind of like a 2d side scroller, and I'm still debating if I should use built in physics.

autumn cipher
#

thanks I'll try it out

valid minnow
#

can somebody tell me why this code for a high score isnt working? basically, i play the game and when i restart it, it shows the previous attemps score, but if i get a score lower than the previous attempt, it still sets the highscore to that number, i tried using an if statement to get around that but its not working idk why

swift falcon
#

is there some kind of method that updates whenever something changes in the given gameobject? New child attached/swapped etc

lucid valley
swift falcon
#

as in rather then check what my character has equipped at all times, to update it when its changed

valid minnow
swift falcon
#

oh, so it should just simply be done at all times?

lucid valley
valid minnow
lucid valley
#

also you'll want to move the if in AddScore to below the adding part

valid minnow
#

that will just set the game score to the highscore tho

lucid valley
#

oh, sorry i'm getting confused

#

i thought you wanted to load the highscore and display it

valid minnow
#

no

lucid valley
#

it's named wrong

valid minnow
# lucid valley oh, sorry i'm getting confused

when i play the game and let's say i get a score of 5, it sets the highscore to five, but when i restart the game and i get a score of 3 it still sets the highscore to 3, even tho it should be 5 because 5 is bigger than 3

lucid valley
#

Highscore vs HighScore

valid minnow
lucid valley
#

use a const string instead

valid minnow
#

ohhh i see ot

lucid valley
#

private const string HighScore = "HighScore";

#

then use that in the functions

valid minnow
lucid valley
#

it's just a variable that can't be changed in script

valid minnow
#

ok

#

thanks for your help i think that should fix it 🙂

lucid valley
#

sorry edited the variable as i did it wrong

#

can't type today it seems

valid minnow
#

yep lol

lucid valley
#

or use interfaces and call it on the parent when you add the child

#

i'll give the two examples

tribal harness
#

is there a code editor for unity or do you have to use visual studio or another?

lucid valley
#

//This script on the parent and the new child will go through this
public void ParentNewEquipment(GameObject equipment)
{
    equipment.transform.parent = transform;

    //Do equip logic you want here
}
lucid valley
tribal harness
#

okay

lucid valley
#

and the other example with interface is

#
//I'm bad at naming stuff so if you have a better name please use it (by convension interfaces start their name with I)
public interface IOnParentChild
{
    public void OnParentChild(GameObject child);
}

//This script on your equipment (where you parent currently)
private void ParentChild(GameObject newParent)
{
    transform.parent = newParent.transform;
    
    //Find all scripts on the new parent which have the interface
    var interfaces = newParent.GetComponents<IOnParentChild>();
    
    //Call the interface for those scripts
    foreach(var parentInterface in interfaces)
    { 
        parentInterface.OnParentChild(gameObject);
    }
}

//On the parent. After the MonoBehaviour see the interface has been added
public class EquipmentController : MonoBehaviour, IOnParentChild
{
    public void OnParentChild(GameObject child)
    {
        //Do logic for when you add equipment
    }
}
#

More complicated but means you can use the interface on any script on the parent and when the child calls the interface it will run on all scripts which implement it on the new parent

#

if that makes sense @swift falcon

swift falcon
#

o thanks. It does make sense, ill look into it

summer pecan
#
    void Date()
    {
        UpdateText("Tuesday\nJuly 12, 2011\n3:27 PM", true);

        Invoke("FadeOut", 6f);
        Invoke("FadeOutText", 6f);
    }

    void Update()
    {
        if (fade == true)
        {
            UnityEngine.Debug.Log("Fading");
            fade = false;
            StartCoroutine(FadeIn());

            Invoke("Date", 4f);
        }
    }

Having an interesting problem here, when invoking the Date function, it will run the UpdateText function, but then will not run the other Invoke commands after it. How can I fix this?

lucid valley
summer pecan
#

Yes

lucid valley
#

did you add logs in FadeOut and FadeOutText to check they arent running?

#

I'd also consider making them all coroutines instead of Invoke, but it should also work using Invoke but i can't see anything clearly wrong with it atm without seeing the whole thing

summer pecan
summer pecan
lucid valley
#

if you have them setup as IEnumerator (for coroutines) then use StartCoroutine

#

thats might be causing the issue with Invoke

#

just have yield return new WaitForSeconds(6f); at the start of those coroutines for the initial 6 second wait

grim flax
#

Hey
I am creating (trying) inventory system and I have problem with NullReferenceException: Object reference not set to an instance of an object
In code it is if (container[i].item)
What is wrong with it? Shouldn't it check if does this item exist?

lucid valley
orchid bane
#

Is there a more graceful way to create an Action delegate than () => {//code}?

lucid valley
#

mostly likely it is the index

orchid bane
#

If the code has several lines

lucid valley
#

so add a null check if(container[i] == null)

summer pecan
grim flax
lucid valley
#

Array, list, dictionary?

grim flax
#

public Slot[] container;

lucid valley
#

an array then

#

ah, you are not initialising it

#

public Slot[] container = new [];

#

might need a capacity i forget

grim flax
#

Yea but do I have to do this when I do it in-editor?

lucid valley
#

that is actually a good question. I usually use lists instead of arrays for inspector stuff

#

so i'm not sure then if it needs initialising

#

lists do, so i'm assuming arrays do to

grim flax
#

Yea first I used lists but after few hours arrays looked better bc I didnt have to set limit or smth

lucid valley
#

but remember that those None as nulls

#

so they will trigger the null reference exception

#

so if you have any for whenever you use that scriptable object it will break

#

i'd just add the null check in the loop to skip that index if its null

grim flax
#

Oh
I forget to mention
In other script I have function Awake that fill those Nones

lucid valley
#

if you are filling all of them then it shouldnt error

#

but if you are not doing it to the capacity it will

grim flax
lucid valley
grim flax
#

Yep

lucid valley
#

then it definitely is due to the array not being initialised

wary ferry
#

Hi yall, trying to figure out ropes with verlet integration, does anyone have any advice on ways to make the rope come to rest when a mass is attached to it? Currently the mass will just bob up and down forever, even with a friction force implemented since gravity is pulling the rigid body down

zinc parrot
#

Is there a way to create large textures in script without causing a huge lag spike? I need to use large textures instead of large rendertextures because large rendertextures are taking 11ms longer to sample in a compute shader vs using large texture2d's and such

#

im talkin like 16k textures(as they are large atlas's)

golden trout
#

Help 😦

if (slots == null)
{
    slots = new ItemSlot[newSlotCount];

    for (int i = 0; i < slots.Length; i++)
    {
        slots[i] = new ItemSlot
        {
            slotItemID = items.itemDic[0].iD,
            slotItemCount = 0
        };
    }
}

I dont understand why this doesent work... I always get this error:

NullReferenceException: Object reference not set to an instance of an object```
The error is the line 313 wich is
```cs
slots[i] = new ItemSlot```
I really dont understand what the problem is...
mossy snow
zinc parrot
#

just their normal constructors

mossy snow
zinc parrot
#

so
new RenderTexture()
new Texture2D()

mossy snow
#

I mean, how are you getting data into them? The actual creation call is slow?

golden trout
zinc parrot
#

yes the creation call is slow
for rendertextures I fill the atlas with a custom texture packer which is fast
then if I wanna use a texture2d, I then need to do Graphics.CopyTexture into the texture2d from the rendertexture

mossy snow
golden trout
mossy snow
#

why do you have to copy texture? Is the Texture2D you're creating readable?

#

it might be slow if it's readable and CopyTexture is transferring data back to the cpu from the gpu

zinc parrot
mossy snow
lucid valley
golden trout
mossy snow
#

you're right Daniel, good eye

#

show us the logging that you "did but cant find anything wrong" with

golden trout
#

When I logg slots.Length, after slots = new ItemSlot[newSlotCount] I get 2 beacouse newSlotCount = 2. If I log slots[i] I get null

lucid valley
#

log the stuff in that

#

items items.itemDic items.itemDic[0]

#

see if any of those is null

golden trout
#

Its = 0 but I can also put a value myself in there. The error stays the same

lucid valley
mossy snow
zinc parrot
#

writing to it from a compute shader

golden trout
#

Or am I understanding something wrong?

lucid valley
golden trout
#

Nope the iD of this item in the Dictionary is 0

lucid valley
#

and that is the line which is erroring

golden trout
#

I can also write it like this for better understanding...

if (slots == null)
{
    slots = new ItemSlot[2];
    
    for (int i = 0; i < slots.Length; i++) 
    {
        slots[i] = new ItemSlot // <---Error is here
        {
            slotItemID = 0,
            slotItemCount = 0
        };
    }
}
lucid valley
mossy snow
lucid valley
#

i just don't believe we could be looking at the right line if thats the case. Theres nothing that could NRE under your changed code

zinc parrot
#

the lag spike comes from recreating the 16k render texture I believe

#

I wish I didnt have to use texture2d's, but its faster to sample from textures when some of them are rendertextures and others are texture2d's in a compute shader

mossy snow
#

did you profile it though? What is the exact time? Are we talking 10ms or 500ms?

golden trout
zinc parrot
#

lemme find out

golden trout
lucid valley
#

ah you just changed it

golden trout
#

Yes

deft bramble
#

So im trying to make it so when an X or O is placed that the winbox GameObject ( which contains winDetectionScript ) will be able to recognize when either an X or O is placed on the winbox, and I tried testing it with print("Thing placed"); but it won't print. The script with Marked() is the one that spawns X and O. The game is tic tac toe incase that helps.

golden trout
#

*The EXACT same

lucid valley
#

if (slots == null) that is currently 307, which also can't error like that lol

golden trout
#

Lol the error just changed

#

It was 313 before...

#

Now its 313 again:

InventorySystem.ChangeSlotCount (System.Int32 newSlotCount) (at Assets/Scripts/ItemManagement/InventorySystem.cs:313)
CraftingController.Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)```
formal bolt
lucid valley
#

You are 100% sure that the debug line does not error?

zinc parrot
lucid valley
#

please try

#

and give me the error line again

#

it should be 317 as the debug is that line now

deft bramble
golden trout
formal bolt
deft bramble
golden trout
# lucid valley please try

Alright Line 313 is now the Debug.LogError line and I get this Error:

InventorySystem.ChangeSlotCount (System.Int32 newSlotCount) (at Assets/Scripts/ItemManagement/InventorySystem.cs:313)
CraftingController.Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)```
lucid valley
#

right now split it up

golden trout
#

split up what? 😅

lucid valley
#
Debug.LogError($"items: {items == null}");
Debug.LogError($"items.itemDic: {items.itemDic == null}");
Debug.LogError($"items.itemDic[0]: {items.itemDic[0] == null}");
#

uh one sec

#

if it is true then it is null

#

(btw if you have a debugger with your IDE this would be a lot simpler)

#

(just using break points instead)

golden trout
#

Error 1:

UnityEngine.Debug:LogError (object)
InventorySystem:ChangeSlotCount (int) (at Assets/Scripts/ItemManagement/InventorySystem.cs:313)
CraftingController:Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)

Error 2:

NullReferenceException: Object reference not set to an instance of an object
InventorySystem.ChangeSlotCount (System.Int32 newSlotCount) (at Assets/Scripts/ItemManagement/InventorySystem.cs:314)
CraftingController.Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)```
https://gdl.space/veqetacele.cs
#

Ok wait I do it again with the new stuff 😂

lucid valley
#

sure

golden trout
lucid valley
#

I use rider but i can try to look up the process

lucid valley
#

it is very good to learn how to do it

#

ah there

golden trout
#

Ah thx

#

Alright here:

Error 1:

items: True
UnityEngine.Debug:LogError (object)
InventorySystem:ChangeSlotCount (int) (at Assets/Scripts/ItemManagement/InventorySystem.cs:313)
CraftingController:Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)

Error 2:

NullReferenceException: Object reference not set to an instance of an object
InventorySystem.ChangeSlotCount (System.Int32 newSlotCount) (at Assets/Scripts/ItemManagement/InventorySystem.cs:314)
CraftingController.Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)```
https://gdl.space/ofixuxitek.cs
lucid valley
#
    void Start()
    {
        items = ItemManagerSingleton.Instance;
        //Other stuff
    }
#

this is returning null

#

are you sure ItemManagerSingleton script exists on a gameobject?

lucid valley
#

how are you setting the Instance

#

show that code

#

is it done in Awake?

golden trout
#

Yup

#

private void Awake()
    {
        itemDic.Add(nullItem.iD, nullItem);
        itemDic.Add(ironOre.iD, ironOre);
        itemDic.Add(ironIngot.iD, ironIngot);

        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }```
lucid valley
#

humm

#

are you spawning it or is it a scene object?

golden trout
lucid valley
#

is the gameobject with InventorySystem also a scene object?

mossy snow
zinc parrot
#

its an atlas of all textures in the scene, I need that because unity doesnt support bindless textures so I cant send an unknown amount of textures to the compute shader

#

and I cant hide a 500ms spike

golden trout
lucid valley
# golden trout yes

huh
The Awake function is called on all objects in the Scene before any object's Start function is called. unity docs

lucid valley
#

so it's a bit weird that instance isnt being set

golden trout
#

But it is set in other functions in the same class...

lucid valley
#

what is going on

golden trout
lucid valley
#

private ItemManagerSingleton items => ItemManagerSingleton.Instance; thats a work around for now

#

see if that works

#

also check to make sure you arent destroying the ItemManagerSingleton at any point

#

if it errors try to find that object in the hierarchy just in case

golden trout
#
public class InventorySystem : MonoBehaviour
{
    private ItemManagerSingleton items => ItemManagerSingleton.Instance;

    //!!!!slotCount should be defined in Engine for each Object!!!
    [SerializeField] private int slotCount;
    public ItemSlot[] slots;

    // Start is called before the first frame update
    void Start()
    {
        //items = ItemManagerSingleton.Instance;
        
        slots = new ItemSlot[slotCount];

        for (int i = 0; i < slots.Length; i++)
        {
            slots[i] = new ItemSlot
            {
                slotItemID = items.itemDic[0].iD,
                slotItemCount = 0
            };
        }
    }

Like this?

lucid valley
#

yeah

#

do you have scene changes?

lucid valley
#

check to see if it exists

golden trout
#

It exists at runntime

#

And before...

lucid valley
#

if you have no scene changes then removing it shouldnt break anything

golden trout
#

Now there are more Errors 😂

lucid valley
#

false means it isnt null

#

you can remove the logs now

#

so something to do with DontDestroyOnLoad(gameObject); is breaking it

#

you could try doing that before you set instance instead of after it

#

might be messing it up somehow, i've got no idea why though

#

or if you are fine without it don't replace it (if you add scene changes then the object would get destroyed)

golden trout
#

Ok if I set it before it works... But why?

lucid valley
#

I have a feeling that the gameobject is cloned and not moved into the DontDestroyOnLoad subscene

#

so the instance is different

golden trout
#

Ah ok that makes sense... Love Unity 😂

#

Alright thank you so much @lucid valley ^^

lucid valley
#

happy to help, even if it does give me a headache :p

autumn cipher
#
RaycastHit[] hits = new RaycastHit[5];
        int numberOfHits = Physics.RaycastNonAlloc(TR.position, TR.forward, hits, float.MaxValue, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Collide);
        Array.Sort(hits, (x, y) => x.distance.CompareTo(y.distance));
        for (int i = 0; i < numberOfHits; i++)
        {
            Debug.Log($"hit {hits[i].collider.gameObject.name}, {hits[i].distance} meters away"); //Line 220
        }
``` hitting anything less than 5 objects gives this error
somber nacelle
#

which is line 220

autumn cipher
#

I've commented it

#

the debug log one

somber nacelle
#

well that doesn't seem right, i would have guessed that it was the Array.Sort call 🤔

autumn cipher
#

numberofHits is accurate despite the debug.log error

lucid valley
#

sort might do it somehow putting the nulls first?

#

not sure how it works internally

autumn cipher
somber nacelle
#

yeah the sort call is probably the reason it is happening if that isn't the actual line the NRE is on.
perhaps you want to use the overload that uses a List so that there are not null entires or null check the objects and loop over the entire array

#

oh turns out there isn't an overload for List like there is for 2d. so i guess you'll have to just null check or try reversing the for loop or sort by descending instead of ascending

autumn cipher
somber nacelle
#

then you'll have to null check or just don't sort the array

lost night
#

Hi I just implemented a basic movement system to my netcode multiplayer game and used Server RPCs for that and when I test it I have an huge input delay. Any ideas where that came from and how to fix that?

somber nacelle
lost night
#

Thanks

#

Why is that under simulation?

autumn cipher
#

weird really

lucid valley
#

that extra pair of {} confused the hell out of me, just for readability

#
        for (int i = 0; i < numberOfHits; i++)
        {
            if (hits[i].collider == null) continue;

            Debug.Log($"hit {hits[i].collider.gameObject.name}, {hits[i].distance} meters away");
        }
somber nacelle
#

or just don't sort the array and it won't be a problem

autumn cipher
somber nacelle
#

why

inner yarrow
#

I created a default actionbased xr origin, but the head isn't tracking. I have imported the default input actions and I can move and rotate the camera with the mock hmd. The issue only happens when I try to actually use a headset. This component is on the Main Camera.

autumn cipher
lucid valley
somber nacelle
autumn cipher
somber nacelle
#

that doesn't answer why you must sort the array

#

your issue is literally because you are sorting it

autumn cipher
somber nacelle
#

so apply the damage after looping through the array if you have to then, or continue with null checking the objects 🤷‍♂️

autumn cipher
autumn cipher
somber nacelle
#

sure it would work, but you can continue with null checking each element of the array if you don't want to put in the effort to make it work

autumn cipher
#

let's say I'm shooting an enemy player through the wall, the shooting order is this:
a metal container -> enemy player -> a wooden plate

lucid valley
#

i think they want the damage to decrease as it penetrates?

autumn cipher
river lynx
#

whats the easiest way to procedurally generate my level? only need to add bacround and a platform in a random location every few units

plain yacht
#

Ok, so I had to reimport the starter assets, and upon doing so the reimport overwrote all the code I had written in my old ThirdPersonController.cs, even though it had been move and renamed ( I guess some underlying id fucked me over bad). Do I have any chance to get my code back, or am I just fucked if it wasn't in version control?

shadow dock
#

I tried following a tutorial, but when he starts typing in code there are suggestion that I don´t get. And when I try to type them out myself, they don´t get the right colour or work properly. any advice?

frigid anvil
shadow dock
#

oh sorry thanks tho

inner yarrow
#

VR Headset not tracking.

valid minnow
#

is there a way to make a trail in unity simulate force in a certain direction without actually moving

valid minnow
# tidal shadow can u reformulate

well, im making flappy bird but my bird doesnt move, it just goes up and down, i wanna add a trail that looks like the bird is moving when its actually not, if i add a trail rn it just goes up and down.

tidal shadow
#

so i understand it as the map is moving from side to side instead of the bird, make a trail at the bird's position and parent it to the map making the trail move with the map?

valid minnow
tidal shadow
#

so you can create the trail and parent it to the map

valid minnow
tidal shadow
#

you position the new part of the trail at the birds position

#

i dont understand 100% how your stuff works

valid minnow
valid minnow
valid minnow
tidal shadow
#

oh

#

then gotta figure out another way to do it

#

didnt really explain how the trail works so...

valid minnow
tidal shadow
#

havent looked into it

valid minnow
tidal shadow
#

the only game trail ive worked with is roblox few years back

valid minnow
#

if i wanted to stop the background and pipes moving when the bird died how would i do that

tidal shadow
#

by checking the state of the bird, if its dead, dont update position of anything but the bird

#

does the bird position actually go up and down?

tidal shadow
#

ok

valid minnow
tidal shadow
#

bruh..

valid minnow
#

💀

tidal shadow
#

where do you update the position of map?

valid minnow
tidal shadow
#

🤦‍♂️ 😆

swift falcon
#

Make your background and pipes move if a bool is true, but when the bird dies set the bools to false

autumn cipher
#

this chatGPT is really scary

#

I've done 2 important game mechanics with it

#

I also feel like crap about it lol

deft bramble
#

you can get actual statistically perfect food recipes from it too

#

How do I make it so this runs everytime a trigger makes a collision, because right now when an X is placed, XWinCondition will go up by 1 but then not add any further when I put down 2 more X's.

toxic notch
#

Anyone know how to add force to a rigidbody along it's local axis? I'm trying to fire a bullet from a gun and the local is pointed correctly but the world is not. I found a snippet online that supposedly converts world to local and tried that but my bullet is firing in the wrong direction. Any ideas?

#

This is what's handling the movement of the bullet:

            _rb.AddForce(localForward * bulletVelocity, ForceMode.Impulse);```
harsh pivot
#

How can I add dragging an object but on fixed path, kinda like a car's stickshift?

proper oyster
toxic notch
#

The problem is the world space direction is not facing the right way

#

only local is

somber nacelle
#

the local forward and world forward point in the same direction, the local forward just uses local space coordinates instead of world space

open crystal
#

Hey all, running into an issue where I am trying to bind Mouse Wheel up and down to switch weapons. I can get a positive or negative value reading based on the direction (-120,120). However when comparing the InputValue value.Get() function, its telling me its not returning an int and I cannot compare it with an int.

#

I see that the Get() function for InputValue returns an object.

somber nacelle
open crystal
#

Im not following, I did see the other Get<>() and trying to pass in int as an argument and get an exception

somber nacelle
#

just to confirm, when you say "pass in int as an argument" you are referring to the generic type parameter on the method, right? and not an argument for the method

open crystal
#

Ive got an input setup for the scroll wheel. My input manager fires off a function when i tick the scroll wheel up or down. if I print the InputValue value.Get(). I do see a value. I cannot use that value to check against an int.

somber nacelle
#

just show what you tried when you used the generic Get

open crystal
#

Debug.Log(value.Get()); // Returns (0.00, 120.00) cant set it to a vector2 Debug.Log(value.Get<int>()); // Returns 0 regardless of scroll direction

somber nacelle
#

my dude, that's a Vector2 not an int

open crystal
#

I cannot assign it as a vector2 either though

somber nacelle
#

why not

open crystal
#

IDE is still telling me that "Cannot convert initializer type 'object' to target type 'UnityEngine.Vector2'

#

lemme cast it

somber nacelle
#

sounds like you're still using Get instead of Get<>

proper oyster
#

why not

value.Get<Vector2>()
somber nacelle
#

but yes, if you insist on using the non-generic version for whatever reason you have to cast

open crystal
#

okay, wow, i see this in rider now, it was only contextually showing me the object get

#

I had to force it after from the menu

#

wow that was really annoying, thank you for the help!

void basalt
#

Is weapon ADSing usually an animation thing or moving cameras?

hollow cosmos
#

Is there a worthwhile difference in performance between:

Vector2 input;

void Update()
{
  input.x = Input.GetAxis("horizontal");
  input.y = Input.GetAxis("vertical");

  // consume the input  
}``` and ```cs
void Update()
{
  Vector2 input;
  input.x = Input.GetAxis("horizontal");
  input.y = Input.GetAxis("vertical");

  // consume the input
}```
sleek bough
#

no, compiler optimizes it

hollow cosmos
#

thanks!

proper oyster
sleek bough
#

Last time I looked it up compiler caches it.

proper oyster
#

ah interesting good to know
not that id had a big infuence if it did not

sleek bough
#

One problematic thing I remember compiler doesn't optimize entirely is for Coroutines, when you create local objects they are not optimized if it's a debug build. But should refresh my knowlends on details on this.

void basalt
#

Is there a way to like add noise to an animation so it's somewhat procedural and always different?

sleek bough
#

Probably have to be code driven for that.

proper oyster
#

either OnAnimatorMove or in a StateMachineBehaviour might be a good palce to add your modifications on top of the animation

#

another option depending on the animation might be a AnimationCurve that you then can use in the code with your noise to drive what ever you want

#

@void basalt

weak prairie
#

I'm having a problem where sometimes when I click on a collider nothing happens - it usually works from different positions, so I assume that some other collider is getting in the way. Is there a good way to figure out what it might be? Or is there a max range for mouse clicks?

orchid bane
#

I constantly get some problems, is it normal?

#

It makes me exhausted

pine horizon
vagrant blade
#

Material material = new Material(""); you haven't specified a shader for your material to use.

pine horizon
#

What kind of shader would solve this problem?

orchid bane
#

Error shader is always pink

#

Just give it a proper one

frosty canyon
#

can anyone help? im kinda new and im not sure where to get starting trying to make it so that i move the red circle to pull and kinda sling them using the blue line kinda help would be apprenticed.

pine horizon
radiant scaffold
#

I don't know where to ask this so I'm just bringing it to general, I've no code errors or anything thankfully but I'm honestly confused on how to move forward with my project. I've made an NPC script using a state machine and one of the states they're supposed to enter is a chatting state when they're close to another npc. I'm trying to figure out how I can check to see if another NPC is nearby so that they can talk to only each other. I want one NPC to be the main chatter and the other one to listen and when the chatting is done I'll change some friendship values. Unfortunately this is way beyond my skill level and I've already tried searching online for similar things or attempting to write it myself to no avail. Does anyone have any ideas?

frigid anvil
hidden kindle
#

I have a issue related to 2D gun mechanics if anyone is willing to help

#

All I want is for the gun to not clip through the ground or push the player up but apparently that is SO HARD

radiant scaffold
#

The issue I'm running into is I need to make the npc enter the chat state (already have that) and wait for another chatter to send feedback back to the script that there's a chatter available

hidden kindle
#

This is the code I have so far with all my attempts that went nowhere

quartz folio
#

Nobody wants to download code. Post it using an external site like the ones linked in #854851968446365696

hidden kindle
radiant scaffold
weak prairie
#

if the total number of chatters is small that will be fine

radiant scaffold
#

No, since the chatting is a state it's not easy to just find object since I made it a substate script pretty much, following the iHeartGameDev fsm tutorial. So it's not something I have stored

#

And I don't think it's something I can just search and iterate through

weak prairie
#

you could make a global container (list, hashset, etc) of objects, then when they enter the chatting state you add them to the container and when they leave the chatting state you remove them from it

radiant scaffold
#

For sure yeah, that'd work I think

#

Cuz then I could see if that chatter is close by

#

And if they are just run the rest of what I need

weak prairie
#

if there are like 50 or more chatters at a time, you'll probably want to figure out something smarter for finding nearby chatters

#

but you can worry about optimization later, just get it working first

radiant scaffold
#

Aye, proof of concept is enough for rn

frigid anvil
#

I mean using tags to identify folks who can chat would be pretty easy.

radiant scaffold
#

I don't think it would work that simply

thorny onyx
#

how do i make code condensed

frigid anvil
#

You boil it until it's reduced by about 30-50%.

thorny onyx
#

i mean in discord lol

#

like the code view thing

frigid anvil
#

🙂 You mean pasting code in the chat, or in a pastebin?

thorny onyx
#

chat

#

you add like <> on it or smthn

#

console.writeline```
frigid anvil
#

Three backticks. ` ` `

thorny onyx
#

ok thanks

frigid anvil
#

Inline, you can do one, surrounding your code.

thorny onyx
#
            
            float mouseX = Input.GetAxisRaw("Mouse X") * 8;
            Quaternion rotationY = Quaternion.AngleAxis(mouseX, Vector3.up);
            Quaternion targetRotation = rotationY;
            transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, 16 * Time.deltaTime);```
#

so

#

i dont know anything about quaternions

frigid anvil
#

Anything longer than a few lines, definitely use a pastebin of some sort.

thorny onyx
#

heres my script to make my gun sway, but the x axis is turned 180 degrees

#

alright

#

so the gun is backwards on the y rotation how can i turn it back, // targetRotation.y -= 180f;
i tried writing that but then the sway wouldnt work

versed marsh
#

how do i update visual studio

swift falcon
orchid bane
thorny onyx
#

i fixed it though by multiplying targetroation by Quaternion.Euler(0,180,0) however theres a giant lag spike every once in a while along with the gun rotating about 10 degrees to the right for a split second before the slerp returns it

orchid bane
#

Feels like the gun's model is placed backwards. The best way would be to fix the model itself or find what causes it to be rotated backwards if the model itself is alright

thorny onyx
#

It could be something weird with the parent object

#

but i put a band aid over that problem

orchid bane
#

oki

thorny onyx
#

why could this lag be happening at the end of this video though ``` float mouseX = Input.GetAxisRaw("Mouse X") * 6;
float mouseY = Input.GetAxisRaw("Mouse Y") * 6;
Quaternion rotationX = Quaternion.AngleAxis(-mouseY, Vector3.right);
Quaternion rotationY = Quaternion.AngleAxis(mouseX, Vector3.up);
//rotationX *= Quaternion.Euler(0, -180, 0);

        Quaternion targetRotation = ((rotationY * rotationX) * Quaternion.Euler(0, -180, 0));
        Debug.Log(targetRotation);

        // targetRotation.y -= 180f;
        transform.localRotation = Quaternion.Lerp(transform.localRotation, targetRotation, 3 * Time.deltaTime);```
orchid bane
#

mkv format come on

#

send an mp4 or something

thorny onyx
#

alr

#

at 29 seconds

orchid bane
#

You can close the tab with asset store you know?

thorny onyx
#

ye ik lol

#

i had it open just before that

orchid bane
#

As for the spike

dusk apex
#

Likely nothing to do with the script you've posted.

thorny onyx
#

happens when i dont shoot too

dusk apex
#

Don't spawn particles and you'll not lag?

thorny onyx
#

particle clone is the particle effect when i shoot the wall

dusk apex
#

Else further investigate

thorny onyx
#

when i dont shoot the wall it still lags

#

i just havent made a destroy command for the particles yes

#

yet

orchid bane
#

Not sure about the particle systems, the count isn't increasing instantaneously after all. I would suggest running Profiler (Window => Analysis => Profiler or Ctrl +7) and then right after the lag press Ctrl+Shift+P, it will pause the game and you will be able to calmly look the Profiler up

dusk apex
#

Just to be clear, the code you posted above has nothing to do with the lag as it isn't really doing much..

thorny onyx
#

when i remove the code there isnt lag, also the unusual rotation of the gun is coorelated to the spikes

dusk apex
#

Show more.. you aren't running this inside some potentially infinite loop are you? Guessing games aren't good. The above code will not "lag" you.

orchid bane
thorny onyx
#

i thought time delta time would only help it im still new to this tho

orchid bane
#

Run the profiler please

#

It will save us all a lot of time

unreal notch
#

hey can someone refresh me on the concept of ref, or make sure my understanding is correct:
when you're using ref like this

void SomeMethod(ref velocity)
{
    velocity = 1;
}```
This means you are directly changing the variable that was sent into this method?
rain minnow
unreal notch
#

thanks

rain minnow
#

Any changes made within the method will reflect on the variable outside of the method . . .

orchid bane
plucky karma
tawny jewel
#

any ideas why isnt this working
Physics2D.IgnoreCollision(Bullet.GetComponent<CircleCollider2D>(), this.GetComponent<CircleCollider2D>(), true);

tawny jewel
#

its not ignoring collision

dusk apex
#

Maybe the bullet isn't what you think it is.

unreal notch
#

asking this out of curiosity now, what is the better way to write this:

//Used in both examples
public class Player : MonoBehaviour

public velocity;
//Example 1
public class Controller : MonoBehaviour

void SomeMethod(ref velocity)
{
    //changes done directly to velocity here
}
//Example 2
public class Controller : MonoBehaviour

[SerializeField] player; //Player.cs goes here

void SomeMethod(velocityToBe)
{
    //changes done directly to velocityToBe here
     player.velocity = velocityToBe;
}

assuming I'm actually getting more done in SomeMethod that just changing one variable, otherwise I think I'd use a return type

tawny jewel
dusk apex
earnest epoch
dusk apex
#

Assuming you aren't getting nre(s).

leaden solstice
unreal notch
earnest epoch
#

Alternatively, check this out:

    private Player _player;
    public velocity {
        get { return _player.velocity; }
        set { _player.velocity = value; }
    }
}```
#

OH, I see.

#

Well, your second example doesn't pass out anything, nor returns a value, so I'm not sure I follow "exporting the delta".

unreal notch
earnest epoch
unreal notch
#

yea

#

logically, I dont see a difference, so it doesnt really matter beyond like, best practice/readability

#

I guess thats what my question should have been; which one is more readable

earnest epoch
#

If you need the player encapsulated within your MonoBehaviour, I would still stick with #2. #1 is only good for when you must work with primitive data by reference, so the actual use case is pretty rare outside of something like smoothing velocity, but in the context of like a method that only calculates a value and leaves it to the developer to choose where it's stored.

#

So because you have a stored player, ref is kind of irrelevant.

leaden solstice
dusk apex
unreal notch
earnest epoch
unreal notch
unreal notch
plucky karma
earnest epoch
unreal notch
#

shhh, I also know the downsides and perils of singletons, I've gotten alot of help with it

#

lol

plucky karma
#

I only ever use it for GameManager.

unreal notch
unreal notch
unreal notch
unreal notch
dusk apex
earnest epoch
unreal notch
#

yea, I didnt explain that very well I guess
I'm using a singleton to make references to commonly used variables across my project
like
GM.i.player can be used to reference my Player.cs script from anywhere

#

so my only dependencies are between GM and other scripts, and never between two other scripts

potent glade
#

can anyone help me with this??
(you can scroll up a bit to see the rest of the question)

earnest epoch
#
        {
            UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
            UnityWebRequestAsyncOperation operation = www.SendWebRequest();
            while (!operation.isDone) { await Task.Yield(); }
            if (www.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("Form upload complete!" + www.downloadHandler.text);
               
                Texture2D xTexture2D = DownloadHandlerTexture.GetContent(www);
                _currentPic.texture = xTexture2D;
                Sprite xSprite = Sprite.Create(xTexture2D, new Rect(0, 0, 200, 200), new Vector2(0.5f, 0.5f));
                _currentPicImage.sprite = xSprite;
            }
            else { Debug.Log("cant retrieve the picture"); }
        }```
Bump
unreal notch
#

I'm not experienced with async unfortunately, I mostly use CoRoutines for the same thing

dusk apex
earnest epoch
#

@potent glade Can you link where you first explain the problem?

unreal notch
#

so if GM gets deleted somehow, my whole game explodes 😛
I mean, yea

#

I kept it in its own scene along with some other core objects

leaden solstice
orchid bane
#

How did Ori's question about refs transform into something about async?

dusk apex
# unreal notch so if GM gets deleted somehow, my whole game explodes 😛 I mean, yea

If anything should happen to that dependent individual, you'd not be able to recover. Further more, if someone (a dev) decides to modify one of the objects managed by the game manager, others would start having issues and potentially think it's the game manager and not the direct culprit. You'd have to ask whoever's managing the manager to further debug. Taking the debugging process one step further. If you change greatly or modify something in one script, you won't just be able to tell your associated references and be done with it.. you'd have to take it up with the manager script that's likely filled with tons of usage of your now obsolete/deprecated data. If you're fine with that, then go for it. I'd rather manage a class once and rarely touch it ever again instead of continuously adding/modifying it - creates potential room for errors (the Manager).

potent glade
#

@earnest epoch the problem is here... I get a texture but it wont show on the the UI image, and when I use a raw image it shows @leaden solstice yes when I use a rawimage i get the correct texture... for some reason the conversion from texture to image seems to be wrong... but i am not sure my method is wrong and i dont know what i should be doing

leaden solstice
potent glade
leaden solstice
#

new Rect(0, 0, tex.width, tex.height)

#

instead of 200x200

potent glade
#

sure

potent glade
fallen lotus
#

i haven't been able to find this online so i wanted to ask. Is there a way to compare a string (name of a scene) and compare it to the list of scenes in the build settings to see if a scene by that name exists? Like basically do something like: if(string sceneToLoad == ASceneInBuildIndex){ DO SOMETHING } else { DO SOMETHING ELSE }

sour trench
#

If I have different NPCs that can be part of quests or simply have dialogue that unlocks something on completion, should I store the "unlocked thing" flag in Inky (this is a 3rd party dialogue system that I'm planning on using that you can store variables in related to your dialogues/story) or a global manager class? I'm struggling to decide.. 🤷‍♂️

cosmic rain
sour trench
#

@cosmic rain How else would you track unlocked things / achievements?

obsidian dust
#

Hello, is there anyone who can help my problem about Photon instantiate???

[PunRPC]
    public void SpawnTelli()
    {           
        PhotonNetwork.Instantiate("MIRANA", spawnPoints[spawnBolgesi].position, Quaternion.identity, 0, null);      
    }
cosmic rain
# sour trench <@209684227720085505> How else would you track unlocked things / achievements?

First maybe define clearly what exactly you want to implement. What you described earlier didn't sound like achievements. Achievements system should probably be implemented separately.
Then there's also ambiguity in terms of when you want to unlock these achievements. If it's on quest completion, it should probably be called(or maybe an event invoked) from your quests systems. If it's on certain dialog it should be triggered from the dialog system. I have no clue about Inky, but I'm sure there must be some way to hook to different events/stages in the dialog.

cosmic rain
obsidian dust
cosmic rain
sour trench
#

@cosmic rain Yeah there is. For example, you could have a quest where you get access to a new ability. But how does the abilities component know what you have unlocked unless there is a boolean flag somewhere that it can check against? And if I'm not going to have a global manager, then what else would I use? It would seem to me like a global manager is the best way unless I'm using some remote database, which I'm not planning on using.

cosmic rain
narrow yoke
#

Hiiii.is there any way to calculate the different between euler angles?

#

what I think is using vector1 * rotation matrix1 and compare with vector2 * matrix2.then get the angle between those 2.I wonder if there's any other easier way or api to calculate Euler angle between Euler angle directly?

cosmic rain
#

If you already have these 2 rotations in euler angles just subtract one from the other. There's really no need to use matrices.

narrow yoke
#

Ohhh.I'm sooo dumb.

#

Thx!dlich

swift yacht
#

FormattingException: Error parsing format string: No suitable Formatter could be found

#

when I use the example {0:list:{}|, |, and }

#

Anyone else have the same mistake ?

lethal plank
#

hi guys
im about to save GameObject for another use in realtime but i will destroy the object i saved so anyway to save GameObject?
hardly to describe so... i have a video describes that

#

because of different attachments so i need to find a way that save gameobject in realtime

#

maybe i need to save it with json?

earnest epoch
#

I'm making some assumptions here, but probably what you need is some sort of manager to hold the prefab references and just have these scripts grab the reference from there.

swift falcon
#

so my chunks turn purple from a distance. awesome! :D
as you can probably see, I'm using a mainly purple texture atlas. don't ask why i made the whole chunk cobblestone.
i think it may have something to do with my UV code which is as follows

public static Vector2[] GetUVCoords(float column, float row)
    {
        return new Vector2[]
        {
            new Vector2((float)(column + 1)/16, (float)row/16),
            new Vector2((float)(column + 1)/16, (float)(row + 1)/16),
            new Vector2((float)column/16, (float)(row + 1)/16),
            new Vector2((float)column/16, (float)row/16)
        };
    }

yeah :/

#

I also had another related-ish issue

#

it seems some of my textures are.. dumbed down?

haughty bough
#
return new Vector2[]
    {
        new Vector2(column + 1, row),
        new Vector2(column + 1, row + 1),
        new Vector2(column, row + 1),
        new Vector2(column, row)
    };
swift falcon
#

i'll try that, but isn't the top right bit of the texture (1,1)?

haughty bough
swift falcon
#

yeah, as expected, it just puts the whole atlas

haughty bough
swift falcon
#

oh also there was this other thing. my textures look oversimplified sometimes.
i get this

swift falcon
haughty bough
swift falcon
haughty bough
#

can you show me only your grass

#

from the atlas

swift falcon
#

here

#

wait it's tiny

haughty bough
#

i see

haughty bough
# swift falcon

not sure but it may be because of the GPU interpolating wrong colors

#

try using mipmapping

swift falcon
simple egret
#

Sounds like something an AI would generate.
Rules were modified a few weeks ago to include one that says

Do not answer using unverified AI-generated answers.
Discard this message if that's not the case.

haughty bough
#

was to lazy to write it myself

swift yacht
#

Is it possible for smart LocalizedString to have a default value if none is passed as argument ?
For example I'd like something like that the smart string " toto {0} {1:"defaultValue"}" with "defaultValue set if you don't pass a second argument

swift falcon
#

also mipmaps are already on

haughty bough
#

ok

#

try to wait for somebody else

#

im helping in beginner

swift yacht
#

Is it possible for smart LocalizedString to have a default value if none is passed as argument ?
For example I'd like something like that the smart string " toto {0} {1:"defaultValue"}" with "defaultValue set if you don't pass a second argument

grim flax
#

Can I ask for something here if it is script with UI problem?

lunar anvil
#

Can I plug in an Object in CoinData if its on another Scene? I move it to this scene with dontdestroy on load)

lunar kestrel
#

Does anyone know why am I getting this error when I open any project ?

gentle hinge
#

Is there a way I can stop an object from impacting another's physics?

#

So that if they collide nothing happens to one

orchid bane
#

Is there any way to listen to an animation event besides having function with the same name on a MonoBehaviour?

knotty sun
gentle hinge
#

I want the objects to collide

#

It's just I don't want one to move the other

knotty sun
iron summit
south crag
#

Alternatively, use triggers

unreal temple
#

Usually preferable to put them on different layers

thin hollow
#

Does Vector2.ClampMagnitude() clamps the sum of the vector components, or its individual axis?
I want to ensure that my vector doesn't go beyond -1 and 1 on any of the axis, would that function be good for that? because I have a suspicion that Vector2 of (1,1) would have length of greater than 1 and these values will get clamped to some fraction in order to shorten it.
Or would it be better to go withVector2 v = new Vector2(MathF.Clamp(v.x,-1,1),MathF.Clamp(v.y,-1,1)) instead?

proper oyster
thin hollow
flat sierra
#

anyone know of any way to disable clicks on a video player, even if i set the layer to ignore raycast or put an invisible image on top of it and disable raycast when i click on it it makes the video kinda goes fowards

potent glade
#

question why am I getting the error that "failed to set the cursor because the specified texture ("cursor2") was not CPU accessible"
I did make the texture as a cursor from the inspector ... what else do i need to do

proper oyster
flat sierra
#

@proper oyster does it say in the input system thing ?

placid obsidian
#

Hiya, I have a projectile which applies a really high force to any rigidbody it hits - would there be an easy way to reduce the force just before the bullet collides?

main shuttle
clever harbor
#

Is it possible to change the pivot point of a generated Mesh?

proper oyster
clever harbor
#

Got it, thanks 😄

rain minnow
versed marsh
#

evertime i type gameobject Plane, plane shows as white and the error says plane wasnt entered, any tips

orchid bane
#

If I make a dynamic Rigidbody Sleep(), will its colliders stop working?

versed marsh
dusk apex
versed marsh
#

?

#

wdym

west sparrow
# versed marsh wdym

See the red underline - if you hover over it, it will tell you what you typed doesn't make sense to it. Your syntax (format) is wrong and it doesn't know what you are trying to do

versed marsh
#

whats syntax

west sparrow
#

I also don't know what you are trying to do so that's all we can tell you

tawny jewel
#

any ideas why are they still colliding?
Physics2D.IgnoreCollision(Bullet.GetComponent<CircleCollider2D>(), circlecollider, true);

versed marsh
#

it says, must contain 2 elements

#

what does 2 elements mean

west sparrow
versed marsh
#

ok, i did that and there is no red line, but it still says the error

west sparrow
#

Assuming you are trying to declare a public variable.

versed marsh
#

yes

west sparrow
#

Youll need to show us the errors to help

#

It might be a quick fix

versed marsh
dusk apex
#

Remove the parenthesis

versed marsh
#

i did

dusk apex
#

They are assuming you're attempting to make a tuple with the parentheses

#

Clear the errors

#

Save the script

versed marsh
#

i just did but it says this

dusk apex
#

Sounds like a different issue

versed marsh
#

oh

#

what do i do]

dusk apex
#

More fixing

west sparrow
# versed marsh oh

Different error. Your variable is Plane but later you typed plane. Capitalization matters

north stag
#

hello, is anyone kind enough to help me with a problem? I'd appreciate it:)

dusk apex
dusk apex
toxic notch
#

Does setting a gameobject inactive cancel invokes? Invoke(DisableMethodName, autoDestroyTime);

north stag
clever mulch
north stag
mental orchid
#

having this issue where lighting/shadows work in editor, but not in build
lighting sort of works in build i.e. color/intensity but shadows aren't getting cast at all
using URP

#

not sure if it matters but my levels are made by instantiating prefabs from assetbundles (its a dungon crawler type game)

marble badger
#

One thing to check is that the quality level you are using in the Editor matches the one you are using in the build, and/or that things work correctly in the Editor at all quality levels (via Project Settings -> Quality).

floral fractal
#

what is this called?, or what should i type for search,
my question is, a standard lerp is moving "straight" from point A, to B, adding animation curve or Easing can manipulate its speed/location based on its ratio(i guess) but still on the "straight line A to B, what i want is move from A to B, with some offset to left or right, or whatever, not a line, thanks

west sparrow
mental rover
polar marten
#

you're tweening

#

you can use DOPath from DOTween to tween a position along a path

vernal prawn
#

My unity keeps crashing, I have an error log but I am having trouble understanding it. Is anyone available to help?

simple egret
regal grove
#

Hey i have a question. Here u c 3 tiles which i want to traverse between. But when I go to the left tile and then I want to go to the middle tile, i'd go all the way to the right. That's why I was trying to have a offset "newPos" to keep track of where exactly i am. But with my current code it does not work at all and moves me to a totally different location

#

with this as code

neat lagoon
# regal grove Hey i have a question. Here u c 3 tiles which i want to traverse between. But wh...

If you have a set number of positions to move to, I would use an array or something similar to store the positions

private Vector3[] m_positions; // all possible positions
private int m_posIndex; // index in array of current position

private void Awake()
{
  var startPos = transform.localPosition;
           
  // could use actual transforms in the scene for these positions, would be better
  m_positions = new[]
  {
    startPos - new Vector3(-5f, 0f, 0f), // left
    startPos,  // center
    startPos + new Vector3(5f, 0f, 0f) // right
  };

  m_posIndex = 1; // set initial index to the middle (assuming you are already there on scene start)
}

private void Update()
{
  if (Input.GetKeyDown(KeyCode.LeftArrow))
    ValidateAndMoveToIndex(m_posIndex - 1);

  if (Input.GetKeyDown(KeyCode.RightArrow))
    ValidateAndMoveToIndex(m_posIndex + 1);
}

private void ValidateAndMoveToIndex(int index)
{
  var newIndex = Mathf.Clamp(index, 0, m_positions.Length); // make sure we can't go outside of the index range in the array
  if (newIndex == m_posIndex) return; // don't move if the new index and the old index are the same (redundant move)
  m_posIndex = newIndex;
  transform.DOLocalMove(m_positions[m_posIndex], 1f);
}
regal grove
twilit hamlet
#

This might just be a weird bad coding practice but I just really want to hardcode a reference to a prefab. Is there anyway or do I really have to drag and drop it in the field?

neat lagoon
#

I also dislike dropping things in fields, so I started using Addressables a while back. This is a package in the package manager. Basically, it let's you define a string for each prefab and load it / instantiate it dynamically at runtime based on the string. Might seem a bit gross but if you follow simple naming conventions and keep constant strings in some static class (or wherever), it's not so bad. (example below)

twilit hamlet
warm night
#

Hey, I have a cinemachine camera. I would like to change the distance. I tried to put a transform further than the Z transform i had before, but it still doesn't work :/ How can I change that?

lucid valley
#

then you just access them via code e.g PrefabStore.MyPopParticles

twilit hamlet
#

Yah, I would but this is like the only thing I need it for and it just seems like a bit to much for an edge case.

lucid valley
#

Well if you only need to do it once then drag and drop once doesnt seem too bad to do?

#

or is this script used on lots of prefabs?

twilit hamlet
#

yah, but im going to be instantiating these classes via code first then loading in the prefabs as objects that have those attributes

#

i.e. saving them as json and loading them

regal grove
#

Like if you can only go from the left tile to the tile above

neat lagoon
regal grove
#

hahah true, id like to try and remake the mario party board system

neat lagoon
#

you would need a tree of nodes that have connections to each other

#

so from any given node you can get the position of its connected nodes

#

and traverse your player through the tree via node positions