#archived-code-general
1 messages · Page 15 of 1
No matter what kind of trickery you use it will always be slower than not using a task
Yeah
Unless you're utilizing thread pool, but you can't do much without Unity API
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
Can I have a disabled object in a list?
Of course, disabled is just a property on the object
what would prevent a disabled object from being in a list? the object still exists and just has a property on it changed
true
I just thought maybe it wouldn't be able to find it to know if it still existed or something
It's just normal C# code, nothing is going to steal the reference from the list
if you're using any of the Find methods you probably won't be able to get a reference to it to put it in the list when it is disabled. but using a better way to get a reference would still allow that
Those methods have overloads to also find inactive objects
not all of them do, and it's only in 2021+
It's definitely been in longer than that
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.
Is there anything built-in in Unity for making quest-like graphs?
Some the GetComponent methods also have the same overload
Like an authoring tool to help you make a graph to use at runtime?
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
yeah
I'm considering chain of ScriptableObjects atm
I'd ask in #↕️┃editor-extensions , unity has an internal experimental graph UI
but it's not very good for visualizing result
I used it to write an ability system and it worked pretty well
is there a stack panel for creating clean menus?
@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
wdym is a Find method? It just iterates the components
because i initially specified that the Find methods wouldn't find it if disabled, so you countered with "bUT gEtCoMpONenT"
Those are the only two "Find" methods...
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
Anyone else spend 5 minutes trying to figure out why something isn’t working only to realize you for a capital letter somewhere
sounds like your IDE is probably not configured, unless your issue is that you are relying too heavily on strings being equal
I’m new so your gonna have explain that
#854851968446365696 has a guide for configuring your IDE (assuming that is what you are referring to)
What was the issue?
I would forget to add a capital letter in the beginning of a word and realize it later after numerous trial and error attempts
Gotcha
if the "words" you are referring to are variable names, method names, or other stuff like that then get your IDE configured. if the "words" you are referring to are just strings then you just need to keep in mind that C# is case sensitive
I keep forgetting c# is case sensitive
Just start using case-insensitive comparisons everywhere 
Ok
(I was joking)
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
Create a script for each "ability" with a common interface and call the required methods for each ability on the robot that was possessed?
I've heard someone use that term before, interface. I don't really know what it is though
In the common language it would mean the interaction point between two systems, in this case your ghost and robot abilities
In C# specifically it means this https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface
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
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.
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
They wouldn't have the same abilities. The types of abilities would be defined by the components on the object, as that is usually the recommended approach for unity
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
If it's not too much, could you expand on the movementability bit? What might GhostMovementAbility look like?
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
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;
}```
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
Tell me if I have this right.
For the ghost, under StartPossession, I'd disable movement, and I'd enable it under EndPossession, then I'd do the reverse for the robot?
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
Sorry, you lost me.
Wait I reread it
I think I maybe understand.
Would the controller be an empty object?
It can be whatever you want it to be, a component on the ghost might make the most sense
Thanks. I think I get it.
Then it could just call GetComponents<IAbility>().ForEach(x => x.StartPossession()) on game start
When the game starts, "possess" the object by calling the StartPossession function on all components that implement the IAbility interface on that object
Wouldn't that possess every object, not just the ghost?
No, it's using GetComponents, which gets the components on the gameobject on which the script is
Oh
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
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);
}
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..
It also doesnt appear in the visual studio dropdown
Does anyone know how to check if a GridBrushBase brush is the currently active brush used by the tilemap editor?
Maybe you can try Regenerate project files under the edit->Preference-External tool
Or reload all
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?
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.
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 😭
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.
How do you want the xml to look?
<language>
<conversations>
<conversation id="generic">
<entry id="con_answer_yes">Yes</entry>
<entry id="con_answer_no">No</entry>
</conversation>
</conversations>
</language>
Try removing [XmlArray("phrases")] from ConversationEntry
And just leave in the [XmlArrayItem("entry"]
^
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
Do you have a set number of TextEntry or is it variable?
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.
How do I figure out how much physics force is needed to push an object from one point to another?
math shudders
unfortunately, yes
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
i dont need it to be super accurate, just passable. I have access to gravity and mass
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 :/
#854851968446365696 tells you how
three `
Meh, I'll go read up 😛
Have you seen this thread on unity? Answer #4
https://forum.unity.com/threads/calculating-velocity-from-addforce-and-mass.166557/
Oh my, it worked! Thanks! I've tried to use [XmlRoot()] before, but I must've been doing something wrong since compiler was throwing an error at me that it isn't allowed.
hmm
I kinda still need help on this if anyone's willing to
How do colliders know if other colliders are nearby?
It would be expensive to simply iterate over all the colliders
What is the problem?
the logic I've written is flawed there, I can't figure it out
does anyone know how I can make it so the player sticks to the platform when the platform is a rigidbody dynamic?
depending on if you are using 3D or 2D physics
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?
they have different use cases
so they are not a replacement for it
Add the player as a parent of the thing that is moving
How is it flawed? What happens?
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
You're decrementing your i value, so when you get to 0 the if else statement damage drop off will be -1
but I'm breaking the loop when i reachs 0
oh you're saying it still gets decremented anyways?
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
= 0 means that the last run will be if i is 0
i > 0 wild make the last one be index 1
But then he will never get his max damage
or clamp the value in
[i - 1]
so that is never below 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];
}
}```
I'm reading thanks
the damage is still max (36) when distance > damDropOff[0]
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];
}
}```
What is the value of hit distance?
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 ?
higher than damDropOff[0], the first damage range
Because for now it's the select button for both of them
These are the results I get from adjusting the distance
after 10 meters the damage should be lowered to 33
guess I gotta use clamp like the other friend mentioned
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
yeah
I still don't understand how I can get index out of range error when I'm breaking the loop when i hits 0
damage = WepData.Damage[i]; is this array equal size?
if (i == 0 && hit.distance <= WepData.DamageDropOffDistances[i])
The distance is still greater than the last element
Yes they are Galtz, you can see them just above
I don't see WepData anywhere. Just Damage and Damage Drop Off Distances
maybe I'm looking at the wrong one?
WepData is the instance of a ScriptableObject
this one
my brain feels like marshmallow right now, thanks for helping
Oh I see it now,
{
damage = WepData.Damage[i];
}```
i - 1 is less than 0
@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
sleep people... Your brain cannot function if you're sleep deprived.
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!
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
what part are you stuck on
I can’t figure out what the script should say to make the scene change happen by pressing E (This is Unity 3D btw)
- Detect whether something is colliding/triggering this
- Condition 1 + isPressing(E)
- Switch the scene
Okay thank you
Is there a way to get a sprite by index on a sliced sprite?
If you have SpriteAtlas you can get sprite by name
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.
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.
dont think u can drag a scene to the inspector
Why exactly do you want to do this? Whats the end goal?
i was trying to add scenes without hard coding them.. I could add them to the inspector and then reference them easier in code
either make a public int representing the build index, or if you prefer you can also reference scenes by string
@buoyant crane so, adding them to the Build Settings, then reference them by their number?
yep that’ll work
thanks!
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?
a disabled canvas
so, if I want the same settings window.. i need to add the this canvas to each scene?
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
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
@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
Well, I dont think a "GameController" would need to know about all your scenes to manage your prefab instances, but if that approach works for you without problems, then it sounds fine
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?
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?
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?
not a bad idea. I'll look more into it.
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!
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
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!
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.
That's very helpful, thank you! I'm primarily doing this out of curiosity so I'll probably explore a couple of the options you mentioned and see what else I can learn. The delineation between assets and packages is much clearer to me now.
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!
Accessing a struct gives you a copy of it, so you would have to assign it back to apply any changes
@grizzled needle Are you sure the reason it doesn't work isn't just that you never initialize testClass inside ClassTwo?
For my case, I need it to be protected! I remembered that structs couldnt be changed that way, but I wanted to make sure.
Sorry, I misread that.. In my test case, I did initialize testClass in ClassTwo. What I typed out was just pseudo code. But it does work exactly as I need it to!
I think the important part to notice here is that your struct is not immutable, the only reason it can't be modified is because ClassOne restricts access to it. You might want to read through https://learn.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code if you want to work with structs.
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
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?
I think you need to elaborate a bit more if we're supposed to understand.
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
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)
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.
The easiest way is to put the input into a Vector2, and normalize it. This forces the vector length to be 1, so you always move at the same speed whatever the input "orientation" is.
input.normalized;
thanks, ill see what i can do
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;
It's how the operator is implemented. Multiplying a vector by a Quaternion rotates the vector and returns it.
so... it would be like (Quaternion.Euler(center_point.rotation.eulerAngles) * Quaternion.Euler(new Vector3(Mathf.Cos(angle_jr) * Mathf.Cos(angle_ir), Mathf.Sin(angle_ir), Mathf.Sin(angle_jr) * Mathf.Cos(angle_ir)))).eulerAngles + center_point.position?
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.
Does the last version do the same thing as first? Since im just wondering how the multiplication of vec by quat works.
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
Yes, it would
I'd be careful with stuff like this - I don't know the implementation enough to say for sure, but converting between quaternions & euler rotations is not a simple 1:1 map, you might end up with some weird behaviour especially with values near 0 or 180 degree rotations
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
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?
thx
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
}```
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.
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?
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
thanks, but i'm trying to make my solution work somehow though, like figuring out what variable specifically i'd want to rotate, since i'm rotating the camera and the gameobject seperately, rather than re-making the entire thing.
#854851968446365696 on how to post code
K
I'm trying to sort an RaycastHit[] based on their distances from PhysicsRayCastNonAlloc(), any non LINQ sources that can help?
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?
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);
}
a loop..
why not use LINQ tho
Bad performance and produces garbage
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;
}
}
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
#854851968446365696 on how to post code
using a interface is one sullution to your problem
you can define a ICanInteract interface that has the interact function
then what ever script has that interface you can interact with
each different item has its own implementation / functionality behind that function
alright cheers, ill see what i can do
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?
@wraith vector Not unless you post the error itself.
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
ah, damn since its on phone (as google play run only on phone build) I can not see the error T.T
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?
Well, I would not really say its an error since when I do Debug.Log(status); I get "InternalError" as the value? 🤔
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:
- Create a DDOL (DontDestroyOnLoad) spawn manager singleton with static methods to spawn a room.
- 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.
- 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.
Awesome, ill check it up! Thanks 😄
can someone help me on where to get the DLL so I can use this function? https://learn.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.getpixel
this again, did you google it
did you first of all try to switch .NET version in unity and see if that fixes it
let me try that
.Where(subClass => subClass.IsClass && !subClass.IsAbstract && subClass.IsSubclassOf(type));``` will this work on Android or ios ?
also you should be able to find the DLL in your systems folder and drag that in your plugins
Yesn't
thank you
Works for non-stripped types
first time for me to physically touch a dll
touch it gently
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
You could use Linq "OrderBy", instead of trying to sort it yourself - there's a bit of GC overhead with Linq, but it doesn't seem like your array is large enough for that to be a concern of performance
if you are going to use the non alloc version then reuse the array. Make hits a variable of the class not a local var
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
I thought local variables were stored in stack
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
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.
thanks I'll try it out
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
is there some kind of method that updates whenever something changes in the given gameobject? New child attached/swapped etc
wdym?
you are never setting the playerpref score to playerScore variable
not to my knowledge
as in rather then check what my character has equipped at all times, to update it when its changed
arent i tho in line 30?
oh, so it should just simply be done at all times?
that is setting the pref
which line do i not state it?
in start add playerScore = PlayerPrefs.GetInt("HighScore");
also you'll want to move the if in AddScore to below the adding part
that will just set the game score to the highscore tho
oh, sorry i'm getting confused
i thought you wanted to load the highscore and display it
no
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
Highscore vs HighScore
what is?
use a const string instead
ohhh i see ot
idk what that is, im extremly new to this stuff
it's just a variable that can't be changed in script
ah
ok
thanks for your help i think that should fix it 🙂
yep lol
you can either do the parenting through a controlling script on the parent so that you can do logic that way
or use interfaces and call it on the parent when you add the child
i'll give the two examples
is there a code editor for unity or do you have to use visual studio or another?
//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
}
have to use external program, unless you do visual coding
okay
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
o thanks. It does make sense, ill look into it
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?
is FadeOut and FadeOutText in the same script as Date?
Yes
can you post the full script using the links in #854851968446365696
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
Yes, I have tried adding a Debug.Log command at the start of them and they haven't logged anything
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
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?
either the container is null or the object at the index i is
Is there a more graceful way to create an Action delegate than () => {//code}?
mostly likely it is the index
If the code has several lines
so add a null check if(container[i] == null)
Ok it's working properly now, thank you for the assistance
is it possible if I am using container.Length in loop?
what type of container is it?
Array, list, dictionary?
public Slot[] container;
an array then
ah, you are not initialising it
public Slot[] container = new [];
might need a capacity i forget
Yea but do I have to do this when I do it in-editor?
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
Yea first I used lists but after few hours arrays looked better bc I didnt have to set limit or smth
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
Oh
I forget to mention
In other script I have function Awake that fill those Nones
if you are filling all of them then it shouldnt error
but if you are not doing it to the capacity it will
Yea I used to do that but then those 'if' were getting same errors
the null check line was erroring?
Yep
then it definitely is due to the array not being initialised
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
this kinda behavior
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)
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...
how are you creating the textures?
just their normal constructors
items is null or itemsDict is null or itemsDict does not have a key of 0 (assuming it's a dictionary)
so
new RenderTexture()
new Texture2D()
I mean, how are you getting data into them? The actual creation call is slow?
nope the Dictionary has a key wich is 0 thats to 100% not the error...
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
one of those conditions is true, so you've made a wrong assumption somewhere. Log it
I did that but I cant find anything wrong
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
wait can I just write directly to it from a compute shader?
you debugged incorrectly, then. Show your logging
in the last case you would get a no key found exception. Instead the error would have a key but with a null value
What do you want me to log?
you're right Daniel, good eye
show us the logging that you "did but cant find anything wrong" with
When I logg slots.Length, after slots = new ItemSlot[newSlotCount] I get 2 beacouse newSlotCount = 2. If I log slots[i] I get null
slotItemID = items.itemDic[0].iD, its this line
log the stuff in that
items items.itemDic items.itemDic[0]
see if any of those is null
Its = 0 but I can also put a value myself in there. The error stays the same
did you not read what i said?
aren't you sampling it? How are you getting data into the RT to start with?
writing to it from a compute shader
I did. When I logg items.itemDic[0].iD I get the value 0
Or am I understanding something wrong?
sorry i though you were checking slotItemCount = 0 somehow when you said = 0
Nope the iD of this item in the Dictionary is 0
right that is very strange if thats the case
and that is the line which is erroring
Its strange beacouse I use the EXACT same code at a different function in the same class and there it works
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
};
}
}
can you literally post the whole script and the error stacktrace
use the links in #854851968446365696
how slow is slow? The docs say readable textures will be copied too, but you're copying from RT -> Texture2D so that shouldn't be an issue
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
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
did you profile it though? What is the exact time? Are we talking 10ms or 500ms?
https://gdl.space/fehinujihi.cs
Error:
InventorySystem.ChangeSlotCount (System.Int32 newSlotCount) (at Assets/Scripts/ItemManagement/InventorySystem.cs:307)
CraftingController.Start () (at Assets/Scripts/Crafting/CraftingController.cs:22)```
lemme find out
link is empty
sry click again
ah you just changed it
Yes
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.
As you can see the same code is used in the startfuncion and there it works...
*The EXACT same
the error line number isnt matching did you change something?
if (slots == null) that is currently 307, which also can't error like that lol
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)```
there's probably something with your colliders going wrong. check 1) does at least one of the colliding objects have a rigid body, 2) are they on colliding layers 3) are they both triggers (only one should be) and double check this article to make sure https://docs.unity3d.com/Manual/CollidersOverview.html
if (slots == null)
{
slots = new ItemSlot[newSlotCount];
for (int i = 0; i < slots.Length; i++)
{
Debug.LogError(items.itemDic[0].iD);
slots[i] = new ItemSlot
{
slotItemID = items.itemDic[0].iD,
slotItemCount = 0
};
}
}
You are 100% sure that the debug line does not error?
it takes 200ms to create the texture2d
and 200ms to do copytexture
please try
and give me the error line again
it should be 317 as the debug is that line now
k so the issue was that they didnt have rigid bodies but now they are falling, do i just get rid of their mass?
Ok give me a sec
if you don't want gravity you can either make it kinematic or set gravity to 0 in your physics settings
I figured it out thanks so much
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)```
ok, so the debug line is erroring
right now split it up
split up what? 😅
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)
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 😂
sure
How do I use on in my IDE?
do you use VS?
I use rider but i can try to look up the process
yes
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
right looking at your code
void Start()
{
items = ItemManagerSingleton.Instance;
//Other stuff
}
this is returning null
are you sure ItemManagerSingleton script exists on a gameobject?
Yes 100%
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);
}
}```
its a scene obj
is the gameobject with InventorySystem also a scene object?
I get similar values. Time can be saved by changing to smaller formats. Can you hide the spike or use a smaller res texture? 16k is absolutely huge
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
And I mean, the void Start() in InventorySystem works. ANd there is the same code....
huh
The Awake function is called on all objects in the Scene before any object's Start function is called. unity docs
yes
so it's a bit weird that instance isnt being set
But it is set in other functions in the same class...
yeah lol, i was just thinking that
what is going on
Yes that is what I ask myself since the last five hours...
😂
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
Yes, it never gets destroyed
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?
Exact same errors as there
check to see if it exists
try removing the DontDestroyOnLoad(gameObject);
if you have no scene changes then removing it shouldnt break anything
its working
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)
Ok, I try
Ok if I set it before it works... But why?
I have a feeling that the gameobject is cloned and not moved into the DontDestroyOnLoad subscene
so the instance is different
happy to help, even if it does give me a headache :p
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
which is line 220
well that doesn't seem right, i would have guessed that it was the Array.Sort call 🤔
numberofHits is accurate despite the debug.log error
I'll reverse the for loop and start from the top
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
reversing the loop didn't work sadly, just tried it
then you'll have to null check or just don't sort the array
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?
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");
}
}
tried this, now it Debug.Logs() only 3 or more hits
weird really
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");
}
you have to loop over the entire array instead of only for the number of hits otherwise you might miss hits that are at the end of the array
or just don't sort the array and it won't be a problem
I must sort it
why
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.
I'm sorting the hits based off of distance to the origin of raycast
do you need the furthest/closest one? If so just find it manually without the sort
for what purpose?
I'm making a wall penetration system for an FPS game
that doesn't answer why you must sort the array
your issue is literally because you are sorting it
because I'll be reducing the damage based on the hitObject's type
so apply the damage after looping through the array if you have to then, or continue with null checking the objects 🤷♂️
Any ideas?
I need all of them in between
that would not work and I'm not fluent enough to explain it in english
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
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
i think they want the damage to decrease as it penetrates?
I need to know which type of (metal, wood etc) object(s) I shot first, in front of the enemy player so I can reduce the damage accordingly
exactly
whats the easiest way to procedurally generate my level? only need to add bacround and a platform in a random location every few units
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?
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?
Configure your IDE. #854851968446365696
Check your IDE settings from #854851968446365696 ; you may not have them set up right.
oh sorry thanks tho
VR Headset not tracking.
is there a way to make a trail in unity simulate force in a certain direction without actually moving
with shaders I guess
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.
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?
yes the map is moving side to side
so you can create the trail and parent it to the map
how will it follow the bird up and down tho
you position the new part of the trail at the birds position
i dont understand 100% how your stuff works
yes but the bird doesnt stay still
ohh i think i get it
how do i parent a trail tho its a component not an object
oh
then gotta figure out another way to do it
didnt really explain how the trail works so...
its just the built in one in unity
havent looked into it
ok
the only game trail ive worked with is roblox few years back
i do have another question for you tho
if i wanted to stop the background and pipes moving when the bird died how would i do that
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?
yes
ok
what function should i use then
bruh..
💀
where do you update the position of map?
nvm lol
🤦♂️ 😆
If(birdDead)
pipeMoving = false
backgroundMoving = false
Make your background and pipes move if a bool is true, but when the bird dies set the bools to false
this chatGPT is really scary
I've done 2 important game mechanics with it
I also feel like crap about it lol
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.
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);```
How can I add dragging an object but on fixed path, kinda like a car's stickshift?
AddForce applies in world space so just using transform.forward of the object you want it to be aligned to should work
the local forward and world forward point in the same direction, the local forward just uses local space coordinates instead of world space
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.
use the generic Get method rather than the one that returns object
https://docs.unity3d.com/Packages/com.unity.inputsystem@0.9/api/UnityEngine.InputSystem.InputValue.html#UnityEngine_InputSystem_InputValue_Get__1
Im not following, I did see the other Get<>() and trying to pass in int as an argument and get an exception
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
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.
just show what you tried when you used the generic Get
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
my dude, that's a Vector2 not an int
I cannot assign it as a vector2 either though
why not
IDE is still telling me that "Cannot convert initializer type 'object' to target type 'UnityEngine.Vector2'
lemme cast it
sounds like you're still using Get instead of Get<>
why not
value.Get<Vector2>()
but yes, if you insist on using the non-generic version for whatever reason you have to cast
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!
Is weapon ADSing usually an animation thing or moving cameras?
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
}```
no, compiler optimizes it
thanks!
are you sure wouldn't creating a Vector2 each update generate garbage?
Last time I looked it up compiler caches it.
ah interesting good to know
not that id had a big infuence if it did not
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.
Is there a way to like add noise to an animation so it's somewhat procedural and always different?
Probably have to be code driven for that.
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
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?
I have the following code: https://pastebin.com/7RBcQEMm
This function is supposed to draw a line from the center of the screen to another point.
Although I specfiy a color, the line is always pink.
How can I fix this?
How can I change the color?
Thanks in advance.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Material material = new Material(""); you haven't specified a shader for your material to use.
What kind of shader would solve this problem?
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.
thanks
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?
So there's a 'distance' check you can do between them, which might be helpful for figuring out if they're close enough to the other NPC. That's easy, from a technical perspective. The other 'friendship values' I assume you already have that conceptually in place. Not sure what you're running into, on that front.
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
Friendship is just an int I can increase so no issue there, I'm using a dictionary to track the friendship value between all the other npcs added to the list so that's fine
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
Nobody wants to download code. Post it using an external site like the ones linked in #854851968446365696
Basically want to check for chatters available within a certain distance and proceed with the chatting but I don't know how I'd start to write that
do you have a list of all chatters in the world? an easy but slow option would be to iterate through all of them and pick one that is close enough
if the total number of chatters is small that will be fine
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
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
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
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
Aye, proof of concept is enough for rn
I mean using tags to identify folks who can chat would be pretty easy.
I don't think it would work that simply
how do i make code condensed
You boil it until it's reduced by about 30-50%.
🙂 You mean pasting code in the chat, or in a pastebin?
Three backticks. ` ` `
ok thanks
Inline, you can do one, surrounding your code.
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
Anything longer than a few lines, definitely use a pastebin of some sort.
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
how do i update visual studio
In the visual studio installer, also not a code question
what do you mean by sway
a slight rotate when i move the mouse
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
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
It could be something weird with the parent object
but i put a band aid over that problem
oki
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);```
You can close the tab with asset store you know?
As for the spike
You see the hierarchy? It's spamming particle clone...
Likely nothing to do with the script you've posted.
happens when i dont shoot too
.
Don't spawn particles and you'll not lag?
particle clone is the particle effect when i shoot the wall
Else further investigate
when i dont shoot the wall it still lags
i just havent made a destroy command for the particles yes
yet
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
Just to be clear, the code you posted above has nothing to do with the lag as it isn't really doing much..
when i remove the code there isnt lag, also the unusual rotation of the gun is coorelated to the spikes
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.
Correlation may be cause by using Time.deltaTime
i thought time delta time would only help it im still new to this tho
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?
Yes, it becomes a reference variable . . .
Any changes made within the method will reflect on the variable outside of the method . . .
how is the profiler thingy there?
A good example can be explained with inner method scope.
e.g.
var val = 5f;
Debug.Log(val); // will say 5
void ModifyThisValue( ref float tmp )
{
tmp = 6f;
}
ModifyThisValue(ref val);
Debug.Log(val); // now this will say 6!
any ideas why isnt this working
Physics2D.IgnoreCollision(Bullet.GetComponent<CircleCollider2D>(), this.GetComponent<CircleCollider2D>(), true);
Define not working.
its not ignoring collision
Maybe the bullet isn't what you think it is.
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
gameobject.findgameobjectwithtag didnt work either
Usually this is where you prove beyond doubt what the bullet is.
I would generally use #2, which is the classic "setter' pattern. Most of the time, ref doesn't see much use in my code and I usually just use out for things where a delta needs to be exported.
Assuming you aren't getting nre(s).
And what is gonna call SomeMethod with ref
You should not use other class field
I think thats irrelevant to the question/answer here, I'm just asking what the better way to export the delta is
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".
exporting the results of whatever changes I want to make to velocity, in this case
Oh, so like straight to the player in this context.
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
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.
Your question makes it about control flow tho
You are passing 'what to set' with the first way so where is the call site matters
With the first, the calling class would need to access the velocity member even if they've got nothing to do with the member. With the second example, the method would be responsible for the object and member. Depends on how you want to couple the data.
well exactly, thats why I dont have a stored player in the ref example
Aaaah... well then as @dusk apex said, this is about data coupling, and not readability. Both are perfectly readable.
very true! I'm aware of this, and the pitfalls you can fall into when using ref
but assuming its used responsibly...
I actualyl dont do that either of these ways, I use a singleton pattern for most of my cross script referencing
Change Player to Movement instead. Implement movement logic inside this class. You should have a function that accepts the direction it needs to go.
Your Controller should only be responsible receiving Inputs. Then create a class that implements the controller, and derive this down into the movement component.
This sounds like DOTS without DOTS... edit: n/m, I was thinking of singletons to act as components (as in ECS) when you wrote "cross script referencing".
shhh, I also know the downsides and perils of singletons, I've gotten alot of help with it
lol
I only ever use it for GameManager.
the class names are kinda red herrings, they are just there for the sake of not everything being a genereicVariableNameHere
the best practices of character movement and input capture arent relevant to my examples, though good advice either way
I've heard of DOTS, but haven't taken the time to really learn what it is
exactly what I'm using it for 😛
They're a pattern that should be avoided as regular referencing should be possible in nearly all cases. Managers (boiler plates - much appreciated but have dependency issues) would be good exceptions.
I took "cross script referencing" to mean something a bit different than what I think you did.
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
can anyone help me with this??
(you can scroll up a bit to see the rest of the question)
{
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
I'm not experienced with async unfortunately, I mostly use CoRoutines for the same thing
The dependency is that of your game manager... objects referencing each other isn't an issue. The issue is when one becomes dependent by many/all..
@potent glade Can you link where you first explain the problem?
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
Do you actually get a correct texture?
How did Ori's question about refs transform into something about async?
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).
sure one sec
@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
Ah, thank you!
And your texture size is 200x200?
the texture size is unknown .. could be anything... but shouldn't the UIimage resize the texture to fit it
Try put
new Rect(0, 0, tex.width, tex.height)
instead of 200x200
sure
IT WORKED! thank you!
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 }
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.. 🤷♂️
Only people that have some experience with Inky could answer that question, and I doubt there are many people like that here(if at all).
But putting something so specific in n a global manager class is definitely a no no.
@cosmic rain How else would you track unlocked things / achievements?
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);
}
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.
Not unless you explain what the problem is.🤷♂️
When i instantiate gameobject with photonnetwork.instantiate and call with RPC. If first player joins no problem but if the second player joins, first players object duplicates
Ok, I see you posted in other channels too. That's crossposting and against the server rules. Please avoid that. Then, there's a specific channel for #archived-networking
@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.
OK, sorry
The ability component shouldn't know about it. Your abilities system should know about it. Maybe subscribe to an event from the quest system. Something like Action<QuestInfo> QuestCompleted, check the quest info for what type of reward it should grant, and if it's an ability, unlock it.
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?
If you already have these 2 rotations in euler angles just subtract one from the other. There's really no need to use matrices.
I'm following unity documentation for localized string but it seems to not work
https://docs.unity3d.com/Packages/com.unity.localization@1.3/manual/Smart/List-Formatter.html
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 ?
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?
Without really knowing how your project works, you probably need to have a reference to the prefab stored somewhere globally and statically accessible so your object can access it on creation or whatever. JSON or trying to serialize the object would be seriously overengineering the problem, though.
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.
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?
You can try changing the code to simply use the column and row values without dividing them by 16
return new Vector2[]
{
new Vector2(column + 1, row),
new Vector2(column + 1, row + 1),
new Vector2(column, row + 1),
new Vector2(column, row)
};
i'll try that, but isn't the top right bit of the texture (1,1)?
tell me if it works
from what i see your materials are the same color
oh also there was this other thing. my textures look oversimplified sometimes.
i get this
it's a texture atlas
didnt see
my actual grass is a bit more detailed
i see
not sure but it may be because of the GPU interpolating wrong colors
try using mipmapping
how
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.
sry then
was to lazy to write it myself
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
will not happen again
i feel responsible for this-
also mipmaps are already on
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
Can I ask for something here if it is script with UI problem?
Can I plug in an Object in CoinData if its on another Scene? I move it to this scene with dontdestroy on load)
Does anyone know why am I getting this error when I open any project ?
Is there a way I can stop an object from impacting another's physics?
So that if they collide nothing happens to one
Is there any way to listen to an animation event besides having function with the same name on a MonoBehaviour?
you could look at the documentation for layer based collisions
in the editor, no. DontDestroyOnLoad is a dummy scene, so you will need to make the reference at run time after Scene Load
thx
I'm trying to make a grapple ability in 2D Top Down Unity which is similar to Akshan's Heroic Swing in league of legends (basically swinging around instead of pulling like a grapple hook), it looks like this right now and I dont understand why its taking me upwards first then downwards instead of one or the other, im just holding left click for a second or two in the gif below:
https://gyazo.com/afcd29fb0db9fc3912d025d3549393c9
You can disable the collision between the two colliders using Physics.IgnoreCollision, https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Alternatively, use triggers
Usually preferable to put them on different layers
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?
depends on what you want
if you want to have the min -1 , -1 and maximum 1 , 1
then you would need co clamp each axis individual
if you want them combined to min -1 and max 1
then ClampMagnitude works for you
Got it, so I'll write a custom function for that then. I suspect that ClampMagnitude() would be great for getting coordinates on a circle.
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
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
what does the video player use for detection inputs on it?
@proper oyster does it say in the input system thing ?
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?
Why not decrease the mass of the projectile or increase the mass of the rigidbody it hits? Your solution seems to work around the issue.
Is it possible to change the pivot point of a generated Mesh?
you would need to move the mesh data ( move the vertecys)
Got it, thanks 😄
How do you check for collision? You can switch the rigidbody type of the hit object, or use a trigger to detect commission and apply the knockback force manually . . .
evertime i type gameobject Plane, plane shows as white and the error says plane wasnt entered, any tips
If I make a dynamic Rigidbody Sleep(), will its colliders stop working?
Show how you've implemented it
plane isnt working
That's improper syntax
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
whats syntax
I also don't know what you are trying to do so that's all we can tell you
any ideas why are they still colliding?
Physics2D.IgnoreCollision(Bullet.GetComponent<CircleCollider2D>(), circlecollider, true);
Remove the brackets? It may be the problem.
ok, i did that and there is no red line, but it still says the error
Assuming you are trying to declare a public variable.
yes
Remove the parenthesis
i did
They are assuming you're attempting to make a tuple with the parentheses
Clear the errors
Save the script
i just did but it says this
Sounds like a different issue
More fixing
Different error. Your variable is Plane but later you typed plane. Capitalization matters
hello, is anyone kind enough to help me with a problem? I'd appreciate it:)
i give up
General response to these types of questions are: https://dontasktoask.com/
ok, so I should just ask
Does setting a gameobject inactive cancel invokes? Invoke(DisableMethodName, autoDestroyTime);
Yes
What’s the problem you are currently facing ?
Never mind I just saw on #💻┃code-beginner 🙂
yes, I couldn't respond sorry. I still can't quite figure how to fix it, I just got a slight understanding of the problem
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)
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).
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
My advice, take a break. Get a coffee or a tea. Disconnect for 20mins and try again later.
Bezier curve?
start with an introduction to C#, you'll find some helpful introductions in the pins of #💻┃code-beginner
you're not lerping
you're tweening
you can use DOPath from DOTween to tween a position along a path
My unity keeps crashing, I have an error log but I am having trouble understanding it. Is anyone available to help?
You can post the log using a paste website (see #854851968446365696). Though if that's the Editor crashing, it's probably not because of your code, so you should move your question to #💻┃unity-talk instead.
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
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);
}
oh damn thanks! I'm gonna look into this
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?
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)
Hmm, I might look into that. Really the only thing I want is this class to not error out when I call this. I wish a public static var would let me put the prefab in the script and that just work
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?
You could make a singleton scriptable object and have it store all the frequently used prefabs
then you just access them via code e.g PrefabStore.MyPopParticles
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.
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?
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
Hey how would this work tho if from 1 tile you can go 3 directions?
Like if you can only go from the left tile to the tile above
Well this is a completely different system haha
hahah true, id like to try and remake the mario party board system