#archived-code-general
1 messages · Page 100 of 1
🙄 it's okay to admit limited knowledge so someone can better help according to that knowledge
for next time. For now just look over the tasks I told you alredy
I already sent what to do
okay
will I get an error if I try to stop a coroutine that is not running?
and if so how do I check if it is running or not?
maybe if you pass a null to StopCoroutine
but i'm pretty sure it's a non-error to stop a coroutine that isn't running, in general
ok, thanks
please ping with response
I want to have a sphere that serves as a boundary for a player. The sphere is large and transparent, and the player is within such sphere. Imagine the sphere is hollow.
I want collision to occur only when the player has collided with the inner surface of the sphere (imagine the sphere is hollow). However, I do not want collision within the sphere. How do I go about this?
So you want basically a sphere collider but with its faces inverted?
Sounds like you need a MeshCollider
Make a sphere mesh, flip its faces/normals and use that as the meshcollider's mesh
Will try—thank you!
Another cheap option is to use a distance check from the center of the sphere to the player and do manual checks that way
But im not sure if thats suitable for your use case. If you need actual collisions, use what I first suggested
Hello, I am watching a tutorial video for Unity and in that video that man wrote a few lines of code and when I wrote the same code I received an error (the video is from 8 years ago) is this because the video is old?
this code:
it looks like gridWorldSize is a Vector2 but you are trying to divide a float by gridWorldSize and store the result in a float. are you certain you don't want to be accessing the individual axes of that vector2?
Basic operators between common types haven't changed in years, so your code is probably different
this is his code:
yours is different
i am blind
var mistake = 2f / new Vector2(10f, 6f);//Error dividing a float by a Vector2 - they cannot operate in this way.```
var mistake = 2f / new Vector2(10f, 6f).x;//Legal - dirty example```
How do I get third person shooting that doesn't shoot around corners like this
I've watched multiple tutorials and they all allow look at where the camera is focused on but it always allows the character to shoot backwards
Whats going on here, are the bullets supposed to fly straight?
you are missing a .x and a .y at the end of those lines
This is the general coding channel, maybe ask your question in #💻┃unity-talk or the forums (assuming you're requesting a feature etc)
Well they seem to be colliding with the player but that's a separate issue
Ok well I can show the code it's just a lot
!code
Use the physics layer matrix to get around that issue
yes...
I can't believe it.
Is the bot down? !code
!code please
hi would anyone spare 5 mins to help me solve one little frustrating and probbably very simple error with my buttons?
Why not ask the question here like everyone else?
People will help if they can
well, it would be easier if ill show it, bcs its probably not only code issue, and i dont want to spam
• Use paste sites to post large blocks of code.
Dalphat is the bot now
Really didn't want to see the screen flood.
Then show it? 🤔
Make a thread if youre concerned about spamminess
This is all the code it's just a lot of like inheritance stuff
oh wait and I need the code for actually shooting the bullet 1 sec
This is the weapon script
The collision stuff isn't working as intended but the shooting technically is, it's just the approach seems to be wrong, but every tutorial I watch tells me to do it like that lol
Without looking too much into the code I would consider checking if the shot direction is in the same direction as the target point. The wall was behind the player but in front of the camera. You can use dot product to determine if they are in the same direction or not - positive would be both facing the same way whereas negative would be the opposite (target was well behind the player!)
ok, i wanted to show somebody on stream but ok, so i have this piece of code. i done it partly with chat gpt bcs i post things here when chat cannot help. ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Przyciski : MonoBehaviour
{
public ProgressBar xp;
public Abilities ability;
private Button button;
void Start()
{
// Get the button component
button = GetComponent<Button>();
// Set the normal color to 110E0E
ColorBlock colors = button.colors;
if (colors == null)
{
colors = new ColorBlock();
}
colors.normalColor = new Color(0.066f, 0.055f, 0.055f);
colors.colorMultiplier = 1;
button.colors = colors;
}
public void OnClickLaser()
{
if (xp.SkillPoints >= 1)
{
ability.laser = true;
ability.laserPoints++;
xp.SkillPoints = xp.SkillPoints - 1;
// Set the button's colors to white
ColorBlock colors = button.colors;
colors.normalColor = Color.white;
colors.highlightedColor = Color.white;
button.colors = colors;
}
}``` later parts are basically the same thing but for different buttons. i want the buttons to be almost black, then when highlited to be white, and when clicked and function is played to stay white forever. my error message is NullReferenceException: Object reference not set to an instance of an object
Przyciski.Start () (at Assets/Skrypty/Przyciski.cs:18)
(its a full one)
ColorBlock colors = button.colors;
So button was null.
And indeed, there's no Button aside this script in the Inspector, so the GetComponent<Button>() earlier fails
Quick tip: GetComponent can return null.
and how do i fix it? im a beginner, thats why i even asked this question
Also note that we don't help with code that's generated by AI
It would return null when you've not got a button on the same object.
the script is attached to both button and canvas
The canvas does not have a button component
For best practices, have the reference variable as public or [SerializeField] private and drag/drop the object into the Editor's inspector field.
You'd remove the GetComponent call if doing so in this way.
ou
Yeah having that script on the Canvas itself isn't logical
ok, i thought that it will aply to children and then i changed the code again so its on every single one of them
so its useless by now
The code explitly says "get a Button on this object", so placing it on an object that has no Button may result in the error you're getting
ok thx its solved
but since im here, ill ask for help with my last error, that is also the same topic, and same error, but with different things
so
ProgressBar.Update () (at Assets/Skrypty/ProgressBar.cs:34)``` my code is ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ProgressBar : MonoBehaviour
{
public HeroKnight heroknight;
public Image ProgressBarImage;
public int AllEnemies;
public int DeadEnemies;
public int PlayerLevel = 1;
public int SkillPoints = 0;
private void Start()
{
// Count the number of enemies in the scene
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
AllEnemies = enemies.Length;
// Call UpdateProgressBar to set the initial progress bar value
UpdateProgressBar();
}
private void Update()
{
// Call UpdateProgressBar every frame to update the progress bar value
UpdateProgressBar();
if(AllEnemies==DeadEnemies)
{
DeadEnemies = 0;
SkillPoints++;
PlayerLevel++;
heroknight.currentHealth = heroknight.maxHealth;
}
}
private void UpdateProgressBar()
{
// Calculate the fill amount based on the number of dead enemies and the total number of enemies
float fillAmount = (float)DeadEnemies / AllEnemies;
// Set the fill amount of the progress bar image
ProgressBarImage.fillAmount = fillAmount;
}
}``` the error occurs when i kill all enemies, so when if(allenemies....) is triggered
it wasnt there before i done my buttons
at Assets/Skrypty/ProgressBar.cs:34
The number 34 above indicates that it occurred on line 34.
but line 34 is heroknight.currentHealth = heroknight.maxHealth;
Wherever that may be
So an NRE occurs when you try to access a member of something null.
heroknight was null (which is fine) but because you tried accessing currentHealth and or maxHealth, the error occurred.
ok sweet fixed that issue thx ppl
Luckily they were both the same reference so you did not have to play guessing games. heroknight was null. Figure out why.
might it be the issue with progresbar not being attached to heroknight?
nah its not it
Your code doesn't seem to assume it would be attached to a heroknight. I would guess that you haven't dragged an object into the Heroknight field in the inspector
obj.Translate(obj.forward * moveSpeed * Time.deltaTime);
why in the world this moves the obj on the global x axis
presumably because obj's z axis is aligned with the global x axis?
Nah it's because .Translate is alrealy local space
ahhh
oh and that
You need to do Vector3.forward * ...
you are right
Vector3.forward * obj.rotation?
- deltaTime, but yes
idk if thats good or bad, couse my problem isnt occured by errors
but atleast now i know whats going on
Thank you!
now I have no idea what direction it's moving. Not on local z axis
Post the new line of code, as well as obj in the scene with the move tool arrows visible, and in Pivot + Local mode
obj.Rotate(obj.up,rotateKosiarka);
obj.Translate(obj.rotation * Vector3.forward * moveSpeed * Time.deltaTime);```
in that rotation it's moving on the global x axis
Still not good, why did you multiply with rotation?
This makes the resulting vector local again
If anyone can help me pls, not sure what is going on. I have a particle effect as a PreFab. If I put it on a missile with a force and when I place the missle in the scene by itself it will fly into another object and explode and the particle effect plays correctly. But I instantiate it from the spaceship, the firepoint is placed WAY of the spaceship object just to test even and as soon as I fire the missile it explodes underneath he ship itself no matter how far out I put the firepoint?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MissileController : MonoBehaviour
{
public float missileSpeed = 30f;
public Rigidbody rb;
public GameObject hitParticlePrefab;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
rb.AddForce(transform.up * missileSpeed);
}
private void OnCollisionEnter(Collision collision)
{
Instantiate(hitParticlePrefab, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}```
Here is the code on the missile to trigger on impact. What am I missing pls?
bah code block didnt work 😦
put the code in code
3 times `
Backticks ```, not quotes
yeah noticed lol sorry
That script is on the root of missile prefab right? Not anywhere else nor any of the prefab's children
how do I convert from whatever Object type LoadAssetAtOath returns to my generic T type?
T prefab = AssetDatabase.LoadAssetAtPath<T>(path);
It gives an error saying there is no type conversion from UnityEngine.Object to T, and no boxing conversion.
Constrain your type to what it needs, at the class declaration: class C<T> where T : Object { }
@simple egret Correct. script is only on missile
Okay, can you Debug.Log the position of the missile when it collides with something? And verify that the position is the one you're expecting (ie. the hit point, not your spaceship pos)
@simple egret Bah good suggestion, thx man. I do that all the time just dont know why I didnt think of doing that now lol.
Im like the Debug god normally lol
@simple egret Thx man fixed it. Got some wierd unknown to man reason I had added a
missile.transform.position = transform.position;. LOL
the missile knows where it is...
Hehe yeah
sure (sorry for the late reply, I got caught up in something)
https://hastebin.com/share/gosaledose.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
try this
void Start()
{
_Agent = GetComponent<NavMeshAgent>();
// _patrolCoroutine = StartCoroutine(Patrol());
PlaceOnNavMesh();
}
// Update is called once per frame
void Update()
{
/*
if (_isChasing == false && IsWithinChaseRange())
{
StartChasing();
}
*/
}```
Can anyone help me with a coding problem?
sorry
this is the basic idea of my app
when you press add a input field comes up asking you to type in how much money you want to add
same for subract
so what's the problem ?
If I have a WebSocketClient that I'd like all my characters to be able to access, what's the best way to do that? A singleton with the instance?
the code part for subtract works but not very correct and the part for adding doesnt work at all
when you subract once it works but subtracting multiple times doesnt add it to the last one just resets it
and the code for adding is the same like for subtracting but it doesnt work
show code
!code
no use a site I can't read lines
it's in the readme
when I run my game on my phone, lock the screen, and turn my phone on again, the game is viewed on top of the lockscreen. Anyone know how to get rid of this "feature"?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using TMPro;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public Text money;
public InputField DODAJ;
public InputField ODUZMI;
public float moneyNumberAdd;
public float moneyNumberSubract;
private float moneyAll;
public GameObject moneyText;
float result1;
float result2;
void Start()
{
Camera.main.clearFlags = CameraClearFlags.SolidColor;
Camera.main.backgroundColor = Color.yellow;
}
public void onClickDodaj()
{
DODAJ.gameObject.SetActive(true);
ODUZMI.gameObject.SetActive(false);
ODUZMI.text = "";
}
public void onClickOduzmi()
{
ODUZMI.gameObject.SetActive(true);
DODAJ.gameObject.SetActive(false);
DODAJ.text = "";
}
void Update()
{
if(moneyAll < 0)
{
Camera.main.clearFlags = CameraClearFlags.SolidColor;
Camera.main.backgroundColor = Color.red;
}
float.TryParse(DODAJ.text, out float result1);
moneyNumberAdd = result1;
Debug.Log(moneyNumberAdd);
float.TryParse(ODUZMI.text, out float result2);
moneyNumberSubract = result2;
Debug.Log(moneyNumberSubract);
if (Input.GetKeyDown(KeyCode.Return))
{
//code for adding
Debug.Log(DODAJ.GetComponent<InputField>().text);
DODAJ.gameObject.SetActive(false);
DODAJ.text = "";
moneyAll = + moneyNumberAdd;
moneyText.GetComponent<Text>().text = " " + moneyAll;
//code for adding
Debug.Log(ODUZMI.GetComponent<InputField>().text);
ODUZMI.gameObject.SetActive(false);
ODUZMI.text = "";
moneyAll = - moneyNumberSubract;
moneyText.GetComponent<Text>().text = " " + moneyAll;
}
}
}
this isn't a code question
It's a unity question that could maybe be solved by code
I said a site from #read me dude
idk
it's not
why not
btw Textmeshpro component comes with functions similar to regex
never heard of regex
you can just make the field "numbers only"
so you dont have to do this
float.TryParse(ODUZMI.text, out float result2);
Also if you're using TryParse, actually use the bool it returns to clear the input if it couldn't be converted to a number!
Or show a message to the user, whatever
okay but why does the subtract code work fine but the add code not
yeah i made it decimal already
but i dont know how i would save it in code
without using tryParse
You need that, or Parse since you're sure it's a number already
parse didnt work
The issue lies in the part where you add or subtract
i honestly dont see it
sorry im new to coding
anyway
moneyAll = +moneyNumberAdd;
change it to
moneyAll += moneyNumberAdd;
^
ohhhhh damnnnn
i feel so fricking dumb
works perfectly fine now
thank you @potent sleet and @simple egret
appreciate it❤️
this is strange though
DODAJ.GetComponent<InputField>().text
DODAJ is already InputField
just do DODAJ.text
And for the parsing, you can do float n = float.Parse(DODAJ.text). It raises an error if what you pass isn't a valid number, but as the input field constrains your input to a valid number, it won't ever raise the error
TryParse is more for the cases where you don't have a constrained input, or you don't trust the user
nope, capsule still going through the floor
You commented out all those things ?
and saved
you saw edit too ?
You should only have
PlaceOnNavMesh();
running in start
yeah, I've realised the true problem, for some reason, the line "_Agent = GetComponent<NavMeshAgent>();" puts the capsule in the floor. I have no idea why seeing as the gameobject it's attached to is not (4.50, 0.08, 0.00) and i dunno where it's getting these coordinates from
do you have any components on the capsule ?
literally the moment I activate the NavMeshAgent, it get's "0.08" on the y axis from somewhere
this is all that's on the capsule
probably the navmesh
but I don't understand "how" that's happening as the navmesh is not at "0.08" on the y axis. So where is that number coming from?
did you disable all movement methods and only get navmeshagent
is there a way to convert this event to hold event?
_decrementButton.onClick.AddListener(OnDecrement);
_incrementButton.onClick.AddListener(OnIncrement);```
Cause it's time consuming when the decrement/increment action only triggers per click. Is there a onPressed function?
also try just
[SerializeField] private NavMeshAgent _Agent;
and setting it in the inspector
yep, it's not moving
so something is wrong in one of the movements scripts
well, I disabled them, so they're not meant to move
make your own button with image component and use
IPointerDownHandler & IPointerUpHandler
yes but now you can narrow down which one is giving issue
is this own button, a new class inherited to Button?
no
you make a script and put those two interfaces with their respective implementation
then use image component instead of Button
ohhh I get it, so its like overriding the default button script
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class MyButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public bool buttonHeld;
public void OnPointerDown(PointerEventData eventData){
buttonHeld = true;
}
public void OnPointerUp(PointerEventData eventData){
buttonHeld = false;
}
}```
you can reference the Image component if you wanna change the sprite
or color
but the pressed/unpressed anim like state will be removed right? the base and pressed color what I meant
read what i wrote under it
well I think it's the warp, but I have no idea why. It says it's "Cannot teleport Guards to (4.50, 0.08, 0.00)" but it shouldn't be warping it there as the floor's position is "0,0,0" so I don't know what's going on. Why does it want to warp there?
the sample position is returning whatever it's trying to warp to
okay thank you, overhaul it is
well, it's meant to be where the Hit navmesh leads, but why is it then telling it to warp at 0.08 at the y axis?
first you added extra Warp above the If statement
try debugging visually hit.position
I have no idea where 0.08 is
nah that's the only warp
bruh
you have 2
on which doesn't belong
the proper usage is the if statement one
also like i said 0.08 sounds like the navmesh height from the ground if ground is at 0,0,0
yeah I think that's what it is
I'm starting to think this is going back to changing the pivot point
the pivot should not matter unless SamplePoistion of 1.0f was too small
which it isn't since it's returning the sampled position
or maybe it didn't
you should debug it since it's an If statement
if(NavMesh.SamplePosition(etc..
...etc
else
Debug.Log("No valid Position on Navmesh found")```
cranked it up to 10 and still same problem
I'm so damn confused
did you try logs
in the sampleposition
if warp is running though it does find a valid position
wait, where do I put this? In PlaceOnNavMesh()?
private void PlaceOnNavMesh()
{
NavMeshHit hit;
if (NavMesh.SamplePosition(transform.position, out hit, 1.8f, NavMesh.AllAreas))
{
_Agent.SetDestination(hit.position);
}
}
just try this
get this instead
it's because hes not on the navmesh
try deleting this agent and make a new one
test same script with new agent
aight bet
okay so I've created a new agent and all, anything I need to change in the script?
no try same line
nope, same error
click the floor and show me inspector tab under Navigation tab , show the Object tab
uh do you have a navmesh surface on the the ground ?
ye
show inspector for that component
Hey folks, anyone have any idea why I cannot see Physics Shape/Body on my project? Pretty much have all thje same packages as the DOTS Sample project but cannot get it to show up...
com.unity.physics@1.0.0-pre65
I have a scriptable object that serializes abstract classes. Though, every time I want to add a new class to the list, I have to recreate the scriptable object. Is there a workaround for this?
public class D_Abilities : ScriptableObject
{
[SerializeReference]
public List<Ability> abilities = new List<Ability>
{
new MagicSeedAbility(), // abstract class
new SummonPlagueAbility()
};
public GameObject abilityPrefab;
}
Write a custom editor script that gives you a UI that can add things to the list
Otherwise there's no way to choose what kind of ability to add in the UI
Hey, I have an array of Spell, which is a struct. I want to either assign it or not depending on the player having a spell equipped at that slot.
How do I check if it's assigned or not?
I tried spells[i] == default(Spell), however the compiler says that I can't compare Spell and Spell (?)
Also heard of nullable value types, not sure how I accomplish that
There are a few libraries that exist to deal with the editor if you just wanna get it over with
I think one of them was called SerializeReferenceExtensions or sumtn
think Odin also has something that does it
- Use a class instead of a struct if you want it to be able to be null.
- Give the struct an "is valid" bool
- use a parallel array with bools
- use an array of nullables
My instinct was to add a bool but that's redundant.
Do you have any idea why checking against default doesn't work?
the bool is pretty much how nullable structs work anyway
Spell[] spells = new Spell[5];
if (spells[i] == default(Spell))
I'm pretty sure they are the same type
Makes sense ^^
Because you haven't implemented any way to compare your structs
You have to define the == operator for it
Ho damn
Equality checking works differently for value types than it does for reference types
Ok, good to know
There's a default comparison for reference types that uses the object address
Structs don't use reference variables so that can't be done in C#
Guys have you got any idea as of why the clamping does not work and it just keeps my vertical movment at 0?
instead of 0 to -90
private void FixedUpdate()
{
float angleY = 0;
float angleX = 0;
if (turning)
{
// Calculate the rotation angle and direction
angleY = turnSpeed * Time.fixedDeltaTime * (turnRight ? 1f : -1f);
}
if (_tilting)
{
// Calculate the rotation angle and direction
angleX = tiltSpeed * Time.fixedDeltaTime * (_tiltUp ? 1f : -1f);
}
// Apply the rotation on global axes
transform.eulerAngles += new Vector3(angleX, angleY, 0);
// Clamp the x-axis rotation between -90 and 0 degrees
Vector3 currentRotation = transform.eulerAngles;
currentRotation.x = Mathf.Clamp(currentRotation.x, -90f, 0f);
transform.eulerAngles = currentRotation;
}```
eulerAngles are interpreted from the quaternion at the time you access them. this means they can be either signed or unsigned depending on how they feel at the time you access it. This also makes clamping an axis on the eulerAngles property after rotating it harder than just manually tracking your rotation as a float and clamping that before assigning it to the rotation
search "clamp rotation" in this discord and you'll see plenty of examples of how you could do so
anyone know why a meshrenderer with its materials array, having two elements in it, will create instanced versions of those materials during runtime? this seems to be what is preventing me from chaning the materials during runtime with a script
how are you trying to change it via script
its the accessing via render.material that is making them instanced
in my script i have Material mat1, mat2, mat3 and so on. the materials are dragged into the inspector.
the script looks like this
tabletMesh = GetComponent<MeshRenderer>();
tabletMesh.materials[1] = mat4;
my code above was my first attempt.
in reply to this suggestion, here is my new code:
tabletMesh = GetComponent<MeshRenderer>();
private void ChangeMat(Material mat)
{
mats = tabletMesh.materials;
mats[1] = mat;
tabletMesh.materials = mats;
}
...//other code///
void Update()
{
if(somethig)
ChangeMat(mat4);
}
accessing materials instantiates the materials and makes them unique to this renderer. that's why they are instanced, bc they only affect this object . . .
this should work . . .
ok, that makes sense. so what is the right way to change the materail during runtime?
you think it should work? darn. its not.
actually i think it is.
hmmm, that's weird . . .
material property block
you mean swap? you can swap material just swap sharedMaterials
material is a getter for the currently used material, if it was unchanged it will return the original shared material, which is the asset
if you assign anything to it it will either assign the new or create a copy
to protect the asset from changes
if you didnt assign anything and didnt change you can just swap shared material for another asset reference
Why am I getting Cannot resolve symbol 'Invoke' and Cannot resolve symbol 'Instantiate'
Like they just don't exist in the context of this interface
But the entire enemy script is based around interfaces so like what am I supposed to do to instantiate the enemy projectiles
Those are methods on Monobehaviour and UnityEngine.Object respectively
If you're writing an interface, they don't exist unless you defined them
Sure, add those to your interface
Like code Instantiate and Invoke myself??
No
Just add them to the interface
Interfaces don't contain implementation
Just the signature
Actually Instantiate is a static method anyway
So there's no need to do anything with Instantiate
wait it's not even an interface
its a class that implements an interface
I could just also get it to inherit from Monobehaviour then right?
Did you forget to derive from Monobehaviour?
I mean sure if you understand what Monobehaviour is
And what that means for your class
I do not really but no red line makes brain happy 🙂
If it breaks later then like
idk what isn't breaking atm
It's one of the most basic things in Unity scripting
Monobehaviours define components you can attach to GameObjects
I mean I just know it as script thing with all the main unity commands
Do you know what a component is
yeah like something you attach to an object
Yes
When you make a Monobehaviour class you're making one of those
If it's not a MonoBehaviour it can't be attached to GameObjects
You have to manage it yourself in code entirely
yh I get that
it doesn't seem like it will mess up the system so yeah it should be fine
Presumably you know if this class is going to be attached to a GameObject or not
If it won't be then it cannot be a Monobehaviour
It matters a lot
Invoke will definitely not work on it for example
Why do you want invoke anyway
yeah ill be real I'm finished bro it
like I just was given a script with a statemachine class
each state is implemented as an interface
and it switches between which state is being executed
Sounds like you're in over your head a little
No shit lol
But it was like the code we were given and it works until I have to extend it to make the enemy shoot instead of just patrol
because shooting requires invoking a firing script on a delay and instantiating a bullet prefab, something the current implementation doesn't seem to allow for
maybe I just put the shooting code in the actual object that holds the state machine
I need some help determining which tile the mouse is over when hovering. This is the code I have so far that seems to be the general goto. But I am having issues with the worldPos result being wonky and not mapping to a proper cell.
var mousePos = UnityEngine.Input.mousePosition;
mousePos.z = 1f;
var worldPos = Camera.main.ScreenToWorldPoint(mousePos);
var mapCell = _terrainTileMap.WorldToCell(worldPos);
var tile = _terrainTileMap.GetTile(mapCell);
if (tile == null) return;
The Grid position is 0,0,0 along with the tilemap within it being 0,0,0. The Camera will zoom in and out as part of the controller. I have been stumped on this for hours and every search result comes up with this same solution. But no matter what, the mapCell is always the same. Im not sure what I could be missing here.
what mode is the camera in, perspective or ortho
It is Perspective
ScreenToWorldPoint will not do what you think then
it gets a point on the near plane of the camera
then you can use the resulting ray, to get a position in the world, by raycasting
Hello. If I have multiple of the same script on one object, how can I reference one of them specifically?
Drag a reference to it into a serialized field
Ah I see with the camera part. I changed it to ortho since I really didnt need it perspective. Now things are changing so I will try working from that. Thanks @quaint rock
it doesnt let me drag it in
are you using the correct variable type?
Then show what you are trying to drag, and to where. Nobody can help without full context.
It's unclear where these two objects are, are they both in the same scene?
one is a prefab
Hello, i think i need an extra pair of eyes.. Here in the video, is an enemy ai, the smaller orange circle is the radius of this next script..
i run a foreach with an overlapsphere and check the players velocity to see if he's moving.. if he is -> we update his position.. if not do nothing.
then cs private void Update() { ForgetSounds(); } runs continuously.. to forget everything after so many Ticks
he shouldn't be updating the player's position unless he's still inside that orange circle.. but here u can see the orange line draws my position until he forgets the sounds.. which is fine, but it should forget the last position he heard the player within that sphere , had the player exited it..
https://www.spawncampgames.com/paste/?serve=code_508
heres the code... something going on in that foreach or something that i dont understand
oh, you can see how the vision one stops and turns magenta when the player exits.. yet the hearing one doesn't 🤔
private void OnDrawGizmos()
{
Gizmos.color = drawColor;
if(DetectedPlayer && Player) // && player
Gizmos.DrawLine(sensePos.position,Player.transform.position);
else if(Player && !DetectedPlayer)
Gizmos.DrawLine(sensePos.position,playersLastKnownPosition);
}``` these are the gizmos
adding in player= null; and DetectedPlayer = false at the beginning of the Tick() fixed it for for not detecting once outside the radius but.. then it breaks the ForgetSounds() function..
imma have to think about this one..
Help required for my AR Game. Look at this code for reference.
https://pastebin.com/iwvJsk0a
This script is attached to an empty GameObject. The function CreatePlayField is assigned to a button's OnClick event. Now the button works, I have tested it with Debug.Log . But it does not generate the plane I want it to in this function. There is a debug.log in Update function I used to know how this function works. That debug statement tells vector difference between positions of a Quad and generated plane. The debug text is empty which alludes that the plane is not generated. The quad is there. The plane is not. Can someone tell what I might be doing wrong here ?
Some screenshots are attached for better understanding
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.
Hey everyone.
So I have this script that chooses a random position in my world and I want to check if that point is inside of a collider. I searched on the internet on how to do it and I ended up with this line of code.
Then, I check if "collider" is null or not and that should tell me if the point is inside a collider or not. But for some reason, it doesn't work, and I'm not sure why.
what doesnt work
the null check? the overlap?
are you sure the collider is on layer 6?
Fairly sure layermask needs to be bitshifted
Try 1 << LayerMask.LayerToName(6)
only if you aren't using LayerMask.GetMask. also LayerToName returns a string which you cannot bit shift anyway
Yep, my Tilemap Collider 2D is on that 6th layer.
The null check always returns false, even though I can see in the scene view that the point is inside of a collider by just spawning an object at that position.
1 << 6
I'm not sure what that means.
Shift it to the left 6 times
i mean a better option than manually bit shifting is just to create a LayerMask variable that you set in the inspector
yes
I'll try that.
also it sounds like you might have a specific collider you are checking against, if that is the case why not use Collider2D.OverlapPoint instead?
0100 0000
Does that mean that 1<<1 is 0000 0001?🤔
Because the script that checks the collision is on a prefab, I thought it would be more effective using Physics2D.OverlapPoint than trying to find my tilemap in the scene to get the collider from it.
ah, fair enough
Works just like before, in the sense that it always returns null.
yep im off to reeducation center
1 << 0 is 0001
UnityEditor.TransformUtils.SetInspectorRotation()
My movement script is messed up. When I try to walk or sprint, I don't move, but if I let go of sprint, I get kind of catapulted forwards and stop slowly. Can someone help?
this sounds to me like you messed up input checks, could you send the code following the #854851968446365696 rules?
It looks like OverlapPoint doesn't work when the Tilemap Collider 2D is used by Composite Collider 2D. 
That was the problem.
hey guys im trying to make a game where the theme is you cant do the same thing twice like walking and i made the controls WASD teleport you a square infront but now i have a issue where i can go straight thru colliders and my script just isnt working to account for that,can someone help https://hatebin.com/crsnjyddze
is it alright to have functions with non capitalized letter at the start
i just saw the naming convention warning but all my functions are already non capitalized
It's not convention to have them lower case start
but would it affect the performance
ah alr then
Functionally not different
Make sure you are consistent with your naming though
It reduces visual load when trying to read your code back
i name my coroutines with capitalized at the start
It instantly becomes clear that you are looking at a function
and functions with non capitalized
Now that's confusing
think that helps to differentiate
i mean it works for me
i saw the warning for coroutine and assumed all coroutines needed pascal
didnt know it applied to functions too
If it works for you then it's fine
Might be worth checking it out
In c# you would usually capitalize them. It's honestly just preference, though. Javascript and such all have them non-capitalized, for example
You can disable the warning, if you would like to stick to it
There's really no "best" way with this. There's just the way that the majority of people considered best practice, and nobody forces you to stick with it
hey I am trying to build a dynamic traffic signal system I am new to unity and I just want to make a simulation does anyone have any base project I can start working on to build the dynamic traffic signal system
sorry about that man, I passed tf out, but here ya go
What base project..?🤨
Anyone know how i might get a sheetmetal effect in unity? and what i mean by that is having the object bending and deforming, but not too bendy.
Want to have it that you can push a mesh like this against a wall and it bends and conforms as it is pushed against the wall.
Hey, morning guys, i've been getting a "A Native Collection has not been disposed..." error regarding memory leak when doing a web request. This has only started showing when I upgraded to 2021.3.6f1, which was a few months ago.
Before we where using 2020.### (don't remember the exact version), but as we upgraded my computer at the start of the year we decided to upgrade the version of unity we where using. Because we had a few other features to work through, I didn't think to address this issue until now. I do have the web request wrapped in a using statement and also call dispose at the end of the call. Even while I do so the error still appears.
It may be obvious to someone else what I might be missing, i'll attach screenshots of the error and the code snippet. If you need any other clarification just let me know.
Do you use native arrays at all?
Also, side note, suggest you look into Newtonsoft when it comes to serializing data to JSON
JSONUtility is very bad
Nope, i'm not at all.
should you really be disposing your webRequest when using implicitly disposes it?
Ahh thanks for that side note, i'll look into Newtonsoft.
I was just thing to think of whats to resolve this issue.
In the stack trace it was pointing to my request script, which is why I thought i would need to dispose somewhere along the line.
Looks like you're not disposing the DownloadHandlerBuffer. Try adding webRequest.disposeDownloadHandlerOnDispose = true
Can Newton Soft handle parse an array json string? Which I currently use a a JSON Helper as a work around.
An array as json that needs to be deserialized into an actual array? Yes
It's one of the many things JSonUtility can't do
You would need to wrap it around an object, lol
There's a whole lot of things it can't do, hence why I strongly suggest you ditch it asap
In the previous screenshot I added it at the end of the using statement for the web request. But the error still shows up.
Which screenshot? You added the upload not the download
also the UploadHandlerRaw also needs the dispose from the looks of it
I was referring to my initial post.
So try removing your manual .Dispose() while keeping both dispose...OnDispose = true
this one.
Yeah exactly you only did for Upload, you need to do it for Download as well
Both of those types, UploadHandlerRaw and DownloadHandlerBuffer mention that they allocate Native Memory. Whenever something allocates native memory you need to dispose it somehow. In your case the UnityWebRequest seem to be able to do it for your through the dispose...OnDispose functions
Amazing, thank you so much, yeah, I was missing just disposing the download. Thank you I was racking my head with this. It makes sense when I think about it, because i'm receiving data too.
I though the using statement would handle that disposing of the data, rather than me having to set the function to true.
a simple traffic simulation project
I'm not sure there's such a thing. At least not for free.
maybe this helps? didnt try it but a quick google search netted this. https://github.com/mchrbn/unity-traffic-simulation
Hey, so I'm trying to do some decoupling, I feel like my stuff is getting really spaghetti'd and I'd like to do a clean up before I continue and make the project bigger.
I have 5 singleton systems/managers, including a GameManager, and they're all just referenced where I've needed them.
Could someone point me to some resources to clean up all my references? Maybe give me the name of a better design method I could research?
Well, it depends on what these managers are doing and where/what for you reference them.
Actually make it 4, I forgot one is just the scene controller, I don't think I need to count that. Lol
I'm doing a kind of idle/resource management game that's all UI based so each of the current singletons are set up for tracking and handling different "resources".
RosterManager handles the minion counts, as well as assigning them to different jobs (sub-rosters).
I have an Income manager that handles everything with the currency; gaining, spending, tracking
Suspicion manager, etc
Stuff like that. I think I've done a pretty good job keeping them all in their own lane, and since everything is UI based, I think most of the game needs to know about what they're doing, I"m just trying to find a cleaner way of getting the data from each of them
You've got a lot of managers. Unless it's multiplayer and you're evaluating the statistics of multiple players, the data could be stored locally on the Players.
do all those objects have a single script and need to be inside the same scenes? if so you CAN just slap all the scripts on one manager object at the very least
They are all currently on their own scene objects and are single scripts
Dependency on third party objects is a boiler plate that I'd avoid unless necessary - ease of access has legitimate uses in game dev but often times is abused.
Yea, I mean I still consider myself to be new at game dev. This is my biggest project so far at like 1200 lines, so it's nothing ridiculous, but I want to learn to do it "correctly" and I can already feel that things are getting kind of messy and tangled, so I'm just looking for options, patterns, etc
Everything is working great though, I have no other issues besides a dirty feeling. Lmao
just work on a paticular problem at a time
Don't want to ruin your fun. Finish it and remake it a dozen times later.
games really do not have a overall approach to follow since things differ much more then in other domains of software
and unity makes traditional dependency managment harder
due to not having just 1 entry point and being able to easily pass stuff down via constructors
We're just mangling a bunch of callbacks and whatnot together..
Alright, that does make me feel better, thanks a lot guys
like everything i do at work is really a big pile of different approaches for different problems
Yea, I'm a dev for a medical software company, but I'm trying to get more into games and it is a very different beast. Lol
also what i do recommend is do not abstract too early
oh cool i worked for a medical device company in the past
hi all, I have this weird thing going on with the tilemap as my player chracter collides with another 2d object. Any idea what it is?
People likely aren't going to download the mkv file. Try mp4 format or something other that would embed into Discord.
Sounds like a perfect pixel issue https://forum.unity.com/threads/flickering-lines-when-my-player-moves.656467/
you can also try setting your scale to 1 - the editor game window scaling can make things look a bit weird
Moving in tiny increments can produce this artifact. There are some work arounds.
[
{
"playerId": "1",
"playerLoc": "Powai"
},
{
"playerId": "2",
"playerLoc": "Andheri"
},
{
"playerId": "3",
"playerLoc": "Churchgate"
}
]
This is the type of array that i'm referring to.
Sorry about the delay got caught up on another task.
But yeah i'm going to take your advice and move to Newtonsoft.
Yeah exactly, JSONUtility can't serialize this
You would need to wrap it into an object
Yeah which is the work around that I've been using. Thanks so much for pointing me in a better direction.
Helping Unity users to a better future, one user a day.
How to disable field sorting in Rider?
I've already removed all "sortBy" inside "fields" in file layout, but it still rearranges fields.
you're using a Navmesh modifier not a navmesh surface :\
In net code is there a way to check if the user is host or a client?
... damn, I'm a fucking idiot 😭
Happens to the best of us
Run into this issue a couple of times now. Anyone know why, when I serialize data using JsonUtility.ToJson(), it just returns a pair of brackets?
Because it probably doesn't know what to do
What are you trying to serialize?
JsonUtility is pretty limited
public struct WorldData
{
public string name { get; private set; }
public Dictionary<string, CharacterData> Characters { get; set; }
[Serializable]
public struct CharacterData
{
public string id { get; private set; }
public string name { get; private set; }
public int credits { get; private set; }
public CharacterData(string id, string name, int credits)
{
this.id = id;
this.name = name;
this.credits = credits;
}
}
It can't handle Dictionaries
It has other limitations
Probably cant serialize a property either
Let me find them
Does WorldData have the [Serializable] attribute?
It does, dunno why I didn't grab it with the c&p
Changed to regular variables, seems to have fixed it:
{"name":"Seb"}
Uh
JsonUtility has the same limitations as any serialization in Unity, it's all the same serializer behind it. That means no properties, unless you have a [field: SerializeField] attribute on it, and fields must be public or have [SerializeField]
Honestly i would just use Newtonsoft.Json but that's your choice
I really should.
its ok we should've checked earlier
Unity really be like "dictionaries who?"
Yeah it's kinda annoying
man, thanks so much for helping me for like 2 whole days bro, I really appreciate it, it works just fine now 😭
np. glad is workin 🥳
oh that's hot
{
"name": "Seb",
"Characters": {
"Sebastian": {
"id": "0",
"name": "Sebastian",
"credits": 10000
}
}
}
Kind of makes you wonder why Unity even bothered making JsonUtility when they could have just baked in the open source NSJS
they did use it internally until recently
now it's just an easy-to-install package
notice how it used to say it's "not supported"
So i wasn't dreaming, it was in the manager at some point
any channel to ask for help or here?
i presume JsonUtility was slapped together a long time ago
When CoreCLR arrives, we can use System.Text.Json 🙏
CoreCLR?
The latest .NET runtime where are the new C# features are being added. Unity is stuck with Mono/.NET Standard 2.1 until they migrate to CoreCLR, which is underway.
Oh cool
3.0 is "verified", whatever that means
https://docs.unity3d.com/2019.4/Documentation/Manual/com.unity.nuget.newtonsoft-json.html
Then maybe I'll get to use System.Random.Shuffle before i become 50
that means they're reasonably sure it'll work properly in that version of unity
huh, that exists?
neat
i've written the fisher-yates shuffle a few timse now lol
Yeah .NET 8
Blackbox it for later, don't make yourself rewrite that over and over
it goes in an extension method :p
but yes, I think i'll just be using the shuffle method now
Watch the shuffle be the same algo
it probably is
the only drawback is that this isn't using UnityEngine.Random
which cooooould be relevant for seeded stuff
but, not really: you'd already have a separate RNG for the shuffling
it's a wash
Well this is an odd example to use. From Wikipedia:
It reminded me of it
i haven't touched that in a while. i am recovering.
cries in php
It's not my job so i guess it helps not becoming crazy
cries in ts
Oh look at you, knowing how to maintain healthy seratonin levels, good job!
I wanted to make a website for my stuff and a friend recommended Svelte which seemed so much easier and friendly that every other popular option
React still gives me nightmares
huge upgrade from js
i can at least understand what my old ts code does
Oh react is easy... its just like html, right... right? 
Would be nice if browsers natively supported TS but, eh.. what can you do?
Hey my first job was vanilla js + jquery, so I know the pain 😄
If i could make everything with C# i would
i have some old js-only web "applications" (scare quotes mandatory)
No one would stop me
i struggle to do anything with them
F# time
You can
With
✨ mawnoh ✨
/s
You can already use it
It's just very shitty to set up
Something about setting up the linker for it to work properly
So totally not worth it
don't be a coward. just serialize data via memcpy.
Yeah? Now reverse it
Wait, I don't know shit, is it really that easy to dump memory in Linux?
Damn it didn't work, you're smart
Skill issue.
it lets you directly read and poke any physical memory address https://man7.org/linux/man-pages/man4/mem.4.html
but anyway, unity,
it hasn't randomly frozen on me in a while on my macbook
Unity is great but the issues can't be ignored eternally
Unity: "I'll fucken do it again"
Uh
I legit never got a crash that wasn't my fault so i guess I'm lucky
I'm really interested in how Minecraft shaders work cause i would really like to make something like them in Unity. They should be lighter than regular realtime lights
I'll have to poke around one
Try telling a struct it can be null and enjoy Unity never not crashing
Have a friend in college learning shaders.
He ELI5, but made it clear it can get very deep and encouraged me to learn Algebra from scratch
shaders are cool
I'm not that great at maths
Since, when I was in high school, I ignored algebra like my mother ignored my father's alchoholism
i need to learn more about writing shaders that are more physically realistic
i mostly just write stuff for special effects
Honestly these are more fun than photorealistic shaders.
I think the pursuit of perfect photorealism is a bit.. toxic?
i do want to make some toon-y stuff
or maybe stealing some visual cues from Hi-Fi Rush
i love stealing visual cues
Some games make realism their main point and forget about gameplay
Is it a game if it's not fun to play?
i saw a tutorial for re-creating its Ben-Day dot bloom effect
Like, go look at the CryEngine tech demo. They focus entirely on graphics. To be fair, that's their whole claim to fame, but there's almost nothing being shown off on the technical side. Oh, you can do ragdoll IK? Mkay.
i can do ragdoll IK by falling out of my chair
Ah, someone who also enjoys crying on the floor. A man of culture, I see.
The floor is underated
Waiting for them to stop bitching that another game studio gave up trying to fix their engine before moving to Lumberyard.
floor is the best rubber duck.
It's been a few minutes without anyone needing help here
devolving into madness
It's not whether they need help, it's the kind of help.
I honestly wonder if someday we'll get multithreading support
Tbh this who chat is leaving me wanting for a gamedev shitposting community
i mean, we've got Jobs
you just can't have 20 threads fighting a battle royale over the scene
hello. so i made climbing scripts for a VR game with gorilla locomotion and i currently have 2 problems.
the 1 one is that if i grab onto something my player is glitching weird (yes the rigidbody is kinematic) and the 2. problem is that if i grab onto a swinging object im not moving with it. i will send a video of how it looks like. appreciate any help.
THERE IT IS
jitter like that makes me think that some stuff is happening in fixedupdate and some stuff isn't
is interpolation enabled for the rigidbody?
i can send the scripts wait
i'm not sure how that'd interact with VR
i've only done like one game jam involving VR lol
these 3 scripts are handling the climbing. it may could be the problem of the gorilla locomotion
damn, called it
I would make VR games and mod existing games into VR if i had a headset
i already fixed some of the lag by putting the "Delta = lastposition - transform.position" in update. it was in lateupdate before
Late update is typically just for camera movement
Are u able to post some of that code on a website, not downloading that on mobile
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
yes
I don't really get what you're doing with the fixed update last = transform.position,
Is your delta value anything other than 0?
It seems like if it is, its gonna be very unreliable to move the player consistently
the delta value is my hands position - position
I see that, but is your delta value working for each frame?
I cant imagine that it does
Plus in your Move() you are multiplying by fixedDeltaTime which is just 1/50
But it's still being called in update
Hey guys and gals. So when I shoot at an enemy, the missile hits the target and the explosion which is in a gameobject container works. But, it is not destroying the effect or the light. Here is the code ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MissileController : MonoBehaviour
{
public float missileSpeed = 30f;
public Rigidbody rb;
public GameObject hitParticlePrefab;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
rb.AddForce(transform.up * missileSpeed);
}
private void OnTriggerEnter(Collider other)
{
Instantiate(hitParticlePrefab, transform.position, Quaternion.identity);
Destroy(gameObject, 1.0f);
}
}``` Is it because the effect is contained in a gameobject as a child and I have to delete the children? Thank you in advance for pointers please.
which line of code destroys the effect or light
@prime sinew I thought once you destroy the main gameobject the effect's are children off they should all be destroyed?
show the hierarchy? what's supposed to be destroyed?
Hey guys, I am trying to implement layered animations in my animator using Animation masks. I am trying to create a combination of rifle put away and walk/run animations. For example, we can draw the rifle while walking or running. What I've done is:
- Base Layer: Consists of the idle/walk/run blend trees (for both with rifle and without rifle)
- Hand Layer: Consists of the mask for only hands and the animation where the player draws / puts back the rifle.
The issue that I am facing here is that when the animation for putting away the rifle finishes the hands of the character stay still for the animation it played using the Hand Layer. Is there any way to fix this ?
What's the hierarchy after the parent is destroyed?
while moving (I have connected the rifle put away to exit and it is looping)
However when I remove the connection with "Exit" state in the state machine this is the result (Second image):
not sure, this seems right. you can try to deactivate the children before destroying the parent though
1 vote and 9 comments so far on Reddit
U shouldnt really have to. The children should get destroyed
We should look into why instead of hacky work arounds for something that should work
thats what I thought
Show the hierarchy after its destroyed
I believe it might be related to the instantiate but not too sure
@lean sail can you elaborate not sure I follow you on "show the hierarchy after its destroyed" pls.
U showed the hierarchy, show it again after destroy() is called
Is your script on the right object
so it does destroy the explosion but not the main gameobject and other children. Script is on the main object the container Explosion3
What is hitParticlePrefab
sorry the script is on the missile not the explosion3 my misstake
hitParticlePrefab is the explosion prefab
ah i guess u have your solution then
ahh I see what I did wrong. Im destroying the hitparticleprefab from the instantiated missile prefab .
Well idk which object is which unless u show the prefab, your script is just on the wrong object
Or you intend to call destroy on the parent
Hey guys. Something weird is happening in my Unity. Before I used to build apk for my game and test them out. I saw the option for patching so i pressed Patch. But it crashed my PC. So, I got back to just Building the apk. But now the Build process crashes my PC after 20 mins. It never took that long to build either. Please help. Its really urgent.
Yupp fixed it. Put a destroy(this.gameobject, 2.0f); on the explosion prefab and that solved the issue. hehe thx guys!
i also had similar issues before. try using a different unity version. if you use 2021.3.1f use 2021.4 or .3.2f like use a similar version
ok. im using 2021.3.9f1
cause exit stop the animations so it freezes
disable the hand layer if your not using it
do that by changing its weight to 0
Guys, I need your help,
I need to make the following code clamp between -90 and 0 degrees on the x but I cant help it
private void FixedUpdate()
{
float angleY = 0;
float angleX = 0;
if (turning)
{
// Calculate the rotation angle and direction
angleY = turnSpeed * Time.fixedDeltaTime * (turnRight ? 1f : -1f);
}
if (_tilting)
{
// Calculate the rotation angle and direction
angleX = tiltSpeed * Time.fixedDeltaTime * (_tiltUp ? 1f : -1f);
}
// Apply the rotation on global axes
transform.eulerAngles = new Vector3(transform.eulerAngles.x + angleX, transform.eulerAngles.y + angleY, transform.eulerAngles.z);
}
Any implementation with Quaternions or something?
Whenever I use them z-axes gets disruppted as well!
I kind of found a work around for that was to transition to an empty state for that layer after the draw animation is finished. I did think of resetting the weight of the layer to 0 but that will be too much code. Thanks anyways for your help 😄
did it work?
I'm using text meshPro and i got this weird bug that I don't understand, so basically I'm cloning an object, and when the cloned object is spawned the text is behind the bubble in my game view, but works completly fine in the scene view
scene view:
Game view:
Any ideas why?
Aight
Check where relative to camera text is spawned
Talking about this?
or this
I meant Z coordinate of the text.
it's 0 and i have tried -1 and 1
The thing is, it works before the cloning
here is the object that I clone in game view
Hey all, I am attempting to use fishnet and XR Interactions toolkit, I am needing to change XR Interactions Toolkit scripts from Monobehaviors to NetworkBehaviors, however in any of the XR Interactions scripts, I am unable to use "using Fishnet.Object", and thus cannot change the script from monobehavior to NetworkBehavior. Any leads on what might be going on here? Is it something with the default assembly?
Xr Interactions toolkit scripts are in their own namespace, if that helps.
I'm moving my question here from #💻┃code-beginner :
I have a building system that allows you to freely place objects, and rn Im trying to make the colliders work. The issue is that the preview is always red (meaning it's colliding). The terrain has the Ground tag (which is layer 9) and the placeable objects have the Building tag. ```csharp
if (Physics.CheckBox(_objToPosition.transform.position, bounds, Quaternion.FromToRotation(Vector3.up, hitInfo.normal), ~(1 << LayerMask.NameToLayer("Ground"))))
{
// Collides
_objToPosition.GetComponent<Renderer>().material = _buildingMatNegative;
return;
}```
Somehow the above if statement still executes true even though the object to position is only hitting the terrain and nothing else.
I've been stuck with this a few hours now and it's driving me crazy
I've tried a lot of different things but none worked
The cube does have a collider
i know this isn't answering your question, but is this little guy based off punpun?
Yup
I'm making a transparent window so Punpun can run around on your desktop
I want to be able to interact with him, but the text isent working
definitely knew i'd seen that somewhere, lovely blast of depression from the past 😭
i hope you get it working, I'd love to test it 🙏
Sure thing man
Most of the functionality works
Just need to fix this and make some more animations
https://pastebin.com/NQ99y9Xv
I have this piece of code which basically implements a grid but sometimes I have problems with removing an element from it.
You can see the debug and condition for it in the Remove method.
This is a typical debug message (almost always the same with exception of position) asd 0, 0, contains: False, wp: (-1.16, 0.00, 1.35), sameList: True, removed: False everRemoved: True, sometimes 0, 0 is something like 2,2
Next there goes ArgumentOutOfRangeException at the line with list.RemoveAt
Any ideas for why it may be so?
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.
Handles class?
For all your gizmo needs https://github.com/vertxxyz/Vertx.Debugging
I don't understand how I use it though
did you read the Usage section of the readme?
well yes, but it doesn't say much on how to use the BoxCast
Do I replace the existing raycast?
You can replace calls to Physics and Physics2D methods with DrawPhysics and DrawPhysics2D to simply draw the results of a physics operation.
Just hypothetically is there a way to detect input via script with the new input system? Like no bindings just like DetectInput GenericGamepad/Whateveryayayawdhiaduawidh?
yes, check the docs in #🖱️┃input-system
oh also, if you want it to be easier, you could use the using alias suggested in the Code stripping section of that same Usage description. This is what I typically do so I don't have to worry about remembering to use DrawPhysics2D instead of Physics2D when using multiple queries in the same class
Hey guys, I need help with something. In my game the camera follows the player by having the exact x and y position as the player every frame, so no lagging behind and catching up. I want the camera to cut off at a certain part of the room (which I have done) and only allow the player to move (with the camera) to the rest of the room after the player has touched a certain object. However, if I immediately set the camera position to the player position once the player touches the object, it will be a hard cut and be jarring. Rather, I want to animate the camera to return to the player, then to resume its previous movement of matching the player's position. I am trying Vector3.Slerp for the animation, but I can't seem to get any code to work. Ideas?
how do I implement that
when u disable one VirtualCamera, and enable another, it'll smoothly translate
if u dont want to use cinemachine u can Lerp the camera to the new position
its pretty simple
in the package manager you can install Cinemachine...
its a unity package..
and then use 1 camera
have it whereever u want it.. and create 2 virtual camera's
thanks
when u wnt it to be stationary.. u switch to the VCAM without the follow code
and then disable it and enable the camera WITH the follow code
it'll automatically transition
why is my visual studio white and errors dont have the red underline and there is no minimize or maximize buttons in top right?
visual studio machine broke
that is an interesting graphical problem
i'd restart your computer first
this happened like a week ago ive just been trying to deal with it
@round palm or u can change the PRIORITY of the virtual camera
and the one with the higher priority will be the one it transitions to.. u can see here the camera im messing with is just there.. the other camera is attached to the player controller..
not even needing to mess with that one..
what it does is.. the virtual camera acts as a place holder.. for where the main camera is positioned
main camera just gets the cinemachine brain component
As for the "no underlines", your projects are unloaded (see the Solution Explorer tab). Right-click them and select "Reload with dependencies" to fix
I inspected the code for the Unity player controllers from their HDRP sample scene, and saw they had something of the sort like:
InputAction receivedInputAction = (InputAction)obj;
InputDevice lastDevice = receivedInputAction.activeControl.device;
_isKeyboardAndMouse = lastDevice.name.Equals("Keyboard") || lastDevice.name.Equals("Mouse");
Which I just made into an event:
private void InputActionChangeCallback(object obj, InputActionChange change)
{
if (change == InputActionChange.ActionPerformed)
{
InputAction receivedInputAction = (InputAction)obj;
InputDevice lastDevice = receivedInputAction.activeControl.device;
_isKeyboardAndMouse = lastDevice.name.Equals("Keyboard") || lastDevice.name.Equals("Mouse");
}
}
Is there a smart way to spawn in a clone but as a child for the Parent?
Some overloads of Instantiate take a Transform as last argument, the Transform it will be parented to.
Ooh nice I didn't know about some of those they'll come in handy later on in this project
I'll look into it, thanks
Does anyone know how I could possibly add a 1D composite binding? Trying to detect D-Pad up and down only and I cant seem to find much on specific paths for bindings
Here's a composite binding example"
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionBindings.html#adding-bindings
Cheers!
Another 1D example here too: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionBindings.html#composite-bindings
Why not just create an Input Actions Asset, then create it in code and bind to events? That's still a full code solution
Hi! I'm making a classic card game, is it worth making each card an ScriptableObject? or just a class and generate the deck is enough?
Quick Question : is it a bad idea to send from the server a json which inside include the list of all the characters of the player and their stats to the client? using tcp
classic card game as in regular playing cards (52 card deck with suits, royals, and numbers)? if so, don't bother making every card a scriptable object, that's certainly overkill. An enum for the suits then either an enum or just straight numbers for the cards would be enough, then making the deck is as simple as a couple of for loops
That's what I thought, thanks
I have a Unity job which does something like:
nativeArray[i * 3 + 0] = GetOne();
nativeArray[i * 3 + 1] = GetTwo();
nativeArray[i * 3 + 3] = GetThree();
But I get:
IndexOutOfRangeException: Index 65 is out of restricted IJobParallelFor range [21...21] in ReadWriteBuffer.
How should I solve it?
I noticed that a simple nativeArray.AsSpan() disables the Unity safety checkings... should I do that?
here's a decent explanation of that error
https://stackoverflow.com/a/70185683/4484008
But my code is guaranted to not collide read/write in the same element.
That's what the NativeDisableParallelForRestriction attribute is for
Ok
Quick Question: how do I set up a check to see if an object is on another object, like a box on a button, to play an animation?
"if an object is on another object" what do you mean exactly?
like, a collision?
like a crate touching a physical button, portal style?
ya, similar
I did the buttons in this video using a trigger collider and an animation:
https://www.youtube.com/watch?v=Tcf6Kafs4Ro
basically an object sitting on top will trigger the trigger collider causing the animator to depress the button
and vice versa
ya. i'm trying to do something like that, just not as a drone
Yep the drone obviously isn't relevant was just giving the video due to my button
I have a 2d character I'm working with, when it was set up it was only given 1 large collision box that was used for both hit-scanning and for world movement collision. I'm assuming it was set up that way because collision boxes are components in unity and a script can really only address one collision box at a time.
I'm wondering what would be the best way to go about setting up several collision boxes like I've drawn. I've done this before in another engine, but there collision boxes were objects not components so it was fairly straightforward to pull all of them into one script.
when a collision event occurs, all components with the appropriately named methods will get that method called
i'd just put them on different objects, and put components on those objects to handle the events
Okay so peep this: I want to make a bestiary in my game but I'm not super sure of the best way to go about it.
Essentially it'd be a book that would slowly fill over time as you meet new creatures, obviously the UI would be a different matter, I'm just not sure of how I would get this done - or am I just looking too deep into it and would it just be a case of a LOT of triggers?
I have a decent idea of what I want, I just need to iron some stuff out
so I'd probably need multiple layers since the hit box and movement box would both be looking for OnCollisionEnter2D ?
yes, you should separate them out by layer
this also requires that they are on separate objects
you could have a list of every enemy type you've found
i'd start with just displaying all of the enemies
figure out that interface first
then worry about hiding ones you haven't found yet
for the separate objects I should just use empty objects nested inside my character?
besides what Chemicalcrux said, you need to also figure out what your learning condition is. Is it just them appearing on screen? Do they have to get into combat with them? do they have to kill them? this condition will determine what mechanics you need to implement to trigger an update in your bestiary.
just seeing them could be a ray cast or a really large trigger collider, combat could be registering a hit or damage on them, death could be interacting with a trigger collider that's enabled on their corpse, there are tons of different approaches.
Bet, thank you kindly
You always want to sperate the Collision (Movement) and the Hitbox. Those operate on two different worlds and do not have the same layer most of the time. It is a good practice for performance, design and maintainability.
yea I wasn't the one who set up the character initially, I'm just trying to fix it now. I've done the above set up in a different engine I just wasn't sure how to go about it in unity since colliders are components. but yea basically I was overthinking the component thing.
Hey everyone, I have a question about the CombineMeshes. I combined a few hexagon planes, it created a single mesh, but it still behaves as if each of the hexagon is a separated object when I apply my Shader that moves the normals. Shouldn't it merge the common vertices into one?
is there a practical means to destroy all components on a gameobject except the transform with consideration for requiredcomponents?
This is expected, combine mesh does not remove triangle and vertices. This function is used for manually batch together meshes to reduce the number of draw calls.
What you are looking for is the concept of boolean operation (Union in your case). Something like: https://docs.blender.org/manual/en/latest/modeling/modifiers/generate/booleans.html
No, there is not. You need to iterate on every component and do the appropriate validation before deleting it. If this something that you are doing in runtime, you might want to find an alternate solution as it is not something that is efficient to do.
Can I achieve that through code in Unity?
I suppose I could just reverse the array of components when clearing them. As long as I only add dependent components so that their dependency is automatically added this should work without issue.
Seems to work, and I can only see this failing if unity changes the order in which dependencies are added to an object.
You should not depend on that. You can use Reflection to find RequireComponent attribut.
what is that
Anyone here well versed in Cinemachine?
Does anyone know how to set the default code that is set when you create a new c# script
ty
MissingReferenceException, I need help
If anyone knows, how would I make an image flash on screen using UI, then the image fades out slowly?
to make it fade out, just lerp the alpha on its color property
or make an animation
Hey guys.
Im doing a jump system and a horizontal move using mobile rotation.
Jump works by clicking once or clicking and hold to jump higher.
When i created the horizontal function the jump holding is not working anymore.
Flux:
private void Update()
{
if (!isAlive)
return;
this.playerJumpInput = Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0);
this.playerJumpInputUp = Input.GetKeyUp(KeyCode.Space) || Input.GetMouseButtonUp(0);
this.playerJumpInputDown = Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0);
if (this.playerJumpInputDown && (IsAnimatorReady() || isSwinging)) isGoingToJump = true; // Jump from ground or vine
isFalling = (this.playerRigidbody.velocity.y < -0.1f) ? true : false;
if (this.playerRigidbody.velocity.y < -10) isRolling = true;
AnimatorHandler();
}
private void FixedUpdate()
{
if (!isAlive)
return;
if (!isSwinging)
{
this.MovePlayer();
}
else transform.position = currentVine.transform.GetChild(0).position;
if (this.isGoingToJump && this.IsPlayerGrounded()) this.Jump();
if (this.isGoingToJump && isSwinging) this.JumpFromVine();
if (this.playerJumpInput && isJumping) this.JumpHigher();
if (this.playerJumpInputUp) this.StopJump();
if (isJumping && this.playerRigidbody.velocity.y < 0f && this.IsPlayerGrounded()) isJumping = false;
HorizontalMove();
}
Jump Code:
private void Jump()
{
Debug.Log("Start Jumping");
isGoingToJump = false;
this.playerRigidbody.AddForce(Vector3.up * this.jumpForce, ForceMode.Impulse);
isJumping = true;
isRolling = false;
jumpTimeCounter = jumpTime;
}
Horizontal move:
private void HorizontalMove()
{
var dirZ = Input.acceleration.x * 20f * -1;
float speed = Mathf.Clamp(dirZ, -20.0f, 20.0f);
Vector3 vel = new Vector3(this.playerRigidbody.velocity.x, this.playerRigidbody.velocity.y, speed);
Debug.Log("vel: " + vel);
this.playerRigidbody.velocity = vel;
}
So i think the problem is that im using add force to jump
it's cs to format for c# syntax highlighting. also use a bin site to share large blocks of code
and when i do the horizontal move and set the velocity of y it stops the impulse
thnks
can anyone help?
This post build script is giving me build errors: https://hatebin.com/cddffctfkh
How to fix :(
Nvm, the fix was to move it to the Editor folder, it worked!
hi, might be a silly question, but i'm just wondering if there's an efficiency difference (or at least a preference) between
class A
{
B b; // assume no nullref
void Method()
{
StartCoroutine(b.DoSomething());
}
}
and
class A
{
B b;
void Method()
{
b.StartCoroutine(b.DoSomething());
}
}
When I try to install my project as apk on Bluestacks it says the version is inappropriate even though it was fine before. I switched to IL2CPP. Any ideas?
there shouldnt be a difference in efficiency, all you would be doing is starting the coroutine on object b instead of a. Only really matters if u disable object A or B
I have a 2D top down game. I'm using TileGrid (so many layers
) to create the landscape, but I want to allow the character to use a shovel to expose dirt, and then expose a hole sprite. Would that mean every tile needs to be a game object?
No, but you'll need to change the tile dynamically. Look up scriptable tiles in unity.
Thanks! I'll look into these
Is burstCompile useful to put on functions which aren't jobs?
In rare cases. If the function satisfies the burst compiler requirements. There's no guarantee you'll get any significant performance improvement from that though. The point of burst is that it makes use of SIMD feature of the CPU.
There aren't any collections in my function
But there are only structs
What do you think?
I mean, you can try and see for yourself.🤷♂️
Doesn't hurt I guess
Sorry about the delay. https://paste.ofcode.org/XTa6z7UGuipKmXcsWncJjd
I got this code off the Unity Marketplace.
It's the Modular First Person pack, so the code should be working. Could it be because I'm in a newer version of Unity?
I don't think that's the case, did you setup the inspector values properly?
code does indeed seem fine but I am quite tired so chances are I am missing something
Inspector seems fine. If you're tired, then I'll stop bothering you if you want.
nah you are not bothering me
I am just saying that there is a chance I'll miss something crucial
did you setup the object as the creator of the asset intended?
and also, are you getting any errors in the console?
I used the player object that was provided in the pack, and the error is NullReferenceException: Object reference not set to an instance of an object FirstPersonController.FixedUpdate () (at Assets/ModularFirstPersonController/FirstPersonController/FirstPersonController.cs:425)
I don't see anything wrong with line 425 in the script, though.
There doesn't have to be anything wrong with the line. It simply tries to access null.
It's just something to do with the sprint bar that I have disabled.
Debug the references on that line to find out which one is null.
Chances are the script requires that very sprint bar and it doesn't execute the rest of the function after that error
yeap
remove that line
I mean those lines
Honestly, if you're asking in #archived-code-general, you're expected to be able to debug the code.
go through the code and see if the sprint bar appears anywhere else
well you are fixing the error that's preventing the rest of the function to execute so it should work
Errors stop execution of the rest of the function, so they should never be ignored.
Now there's this error. Assets\ModularFirstPersonController\FirstPersonController\FirstPersonController.cs(520,1): error CS1022: Type or namespace definition, or end-of-file expected. There is absolutely nothing wrong with line 520. It's just a }
You've probably deleted/commented out a brace or something...
Or added one extra
It's the end of the script, though. Should there be anything other than a squiggly bracket?
The compiler counted the opening and closing brackets in the script and found out that there's one extra(or missing). It doesn't have a way to know which one it is(since that depends on the logic in your code), so it points to the last bracket.
Although that's just an assumption. It could be some other syntax error. Impossible to tell without seeing your code...
Ok, I fixed every error except one, and I don't understand it. Assets\ModularFirstPersonController\FirstPersonController\FirstPersonController.cs(436,5): error CS8803: Top-level statements must precede namespace and type declarations.
This is the line of code it's talking about: void CheckGround()
do you have a good recent resource for this? all the videos I find are multi-year old
The unity manual.
It sounds like some code appears to be somewhere it does not belong. Code outside of a class or method which should be inside a class or method body, among other things. Could just be an extra or misplaced closing bracket. Your IDE should provide some highlighting and insight into the problem?
I don't think there are any misplaced brackets, and this void is in the same place relative to the rest as all the other voids. ```void CheckGround()
{
Vector3 origin = new Vector3(transform.position.x, transform.position.y - (transform.localScale.y * .5f), transform.position.z);
Vector3 direction = transform.TransformDirection(Vector3.down);
float distance = .75f;
if (Physics.Raycast(origin, direction, out RaycastHit hit, distance))
{
Debug.DrawRay(origin, direction * distance, Color.red);
isGrounded = true;
}
else
{
isGrounded = false;
}
}```?
Share the whole script.
also show where your IDE underlines an error
can anyone help me here?
There's an extra closing bracket in the method above CheckGround(), which results in the previous method and class body closing early. The compiler thinks void CheckGround() is outside of the class, because it is
your code is hard to read on discord, but you should add debugs to see what input exists at once. Like if your jump holding gets canceled by pressing horizontal movement. I dont see any specific issue with your HorizontalMove
also pls format your code to be more readable, it may seem concise to you for anyone else its difficult to read
also just nitpicking, but this ternary doesnt need to exist
isFalling = (this.playerRigidbody.velocity.y < -0.1f) ? true : false;
the boolean expression
(this.playerRigidbody.velocity.y < -0.1f)
already returns true or false
i fixed it hardcoding a instant velocity when jumping instead of just waiting for the impulse force eheh
now im dealing with a situation
why velocity got stoped everytime it is colliding with a wall?
or any other object
i want it to keep falling, even if it is colliding with a wall
i just want it not to go trough the wall
do u have a physics material on your collider? i assume this is because of the friction
no
if you want it to slide off the wall then u need a frictionless material
u can create a physics material and just set it to 0 then put it on the colliders
thnks very much 😉
Hey good day.
I have a dijkstra matrix (chess board with numbers representing distance from a point to that square) and i wanted to make a color gradient using that info, is there any way of doing so without needing materials for each distance nor shaders?
have a look into https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html
iirc there's a problem with it in that you can't batch materials if you use it, which sort of defeats the entire point of the optimisation, so perhaps there's something better out there
I will, thanks. And dont worry i dont care to much about optimization for now
Hi why is CharachterController.isGrounded is not reliable and is there a solution 4 it
i answered you in #💻┃code-beginner , dont need to crosspost a beginner question here
Is there a way to have different camera use different quality levels? eg one camera renders on low and one renders on high. trying to do a LOD kinda thing where portal screens render in lower quality when they're further away
Hello good day, I have a game which has multiplayer in it using Netcode for GameObjects. I used to make the server build and the client build from the same project. This used to work when the project initially had no other third party plugins but I went ahead and added mediation and what not to the project, without thinking about how it could effect the server build. Now, I am unable to make a server build specifically a linux server build since plugins like AppLovin (an adk sdk) don't support these platforms. How do I salvage the project now? Also, how do you guys handle server/client architectures and third party plugins? Thank you for your input
I keep getting MOVING FILE FAILED - access denied errors when I attempt to open my unity project after a format. 5 years of work gone? Have rebuilt temp/library folders still same
5 Years of work gone? Are you not using source control?
What do you mean by "after a format"?
Just pull the latest version from Git. If you haven't made backups in 5 years then that's on you
I have the latest backup. I had to reinstall windows on a new drive, along with unity and hub. Tried to load my project (different HD) and get errors as above
Unity may not have sufficient rights to move files. Try running it as administrator and see if that fixes the issue. Also check your Hub configuration, it might be trying to move files from folders that don't exist anymore