- Home /
How do I make my for each loop go through all my points?
I have a code that spawns "pixels" at every position between 0 and 10 in the x, y, and z direction with a step of 0.4. I am trying to change the transparency of certain "pixels" based on a text file. When I run this file, only the last "point" has the correct transparency. Here is my code:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.IO;
using System;
using System.Runtime.InteropServices;
public class FileManager : MonoBehaviour
{
public Renderer rend;
float[] lines;
string filePath, fileName;
void Update()
{
if (Input.GetMouseButton(0))
{
fileName = "Wave_Time_3.txt";
filePath = Application.dataPath + "/" + fileName;
ReadFromTheFile();
}
}
public class Point
{
public float x { get; set; }
public float y { get; set; }
public float z { get; set; }
public float p { get; set; }
}
public void ReadFromTheFile()
{
List<Point> Points = new List<Point>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach(var line in lines)
{
string[] entries = line.Split(',');
Point newPoint = new Point();
newPoint.x = float.Parse(entries[0]);
newPoint.y = float.Parse(entries[1]);
newPoint.z = float.Parse(entries[2]);
newPoint.p = float.Parse(entries[3]);
Points.Add(newPoint);
}
Color color = this.GetComponent<MeshRenderer>().material.color;
rend = GetComponent<Renderer>();
foreach (var Point in Points)
{
if (transform.position == new Vector3(Point.x, Point.y, Point.z))
{
rend.enabled = true;
color.a = Points[0].p;
this.GetComponent<MeshRenderer>().material.color = color;
}
else
{
rend.enabled = false;
}
}
}
}
Here is the content of my text file:
4.75 , 5.00 , 5.00 , 0.04361341
5.00 , 4.75 , 5.00 , 0.04361341
5.00 , 5.00 , 4.75 , 0.04361341
5.00 , 5.00 , 5.00 , 0.99263654
5.00 , 5.00 , 5.25 , 0.04361341
5.00 , 5.25 , 5.00 , 0.04361341
5.25 , 5.00 , 5.00 , 0.04361341
Answer by Deivore · Jul 30, 2020 at 11:01 PM
Is something meant to be moving the FileManager object around? If not, it looks like the if statement code will only be executed if the point happens to have the same location as the FileManager's transform, which is a potential problem.
Additionally, the MeshRenderer attached to the FileManager's object is having its material's color set to different values, each of which will override the previous color value: the material only has one color value at a time. It sounds like what you are looking for is a way to set the values of different pixels, which means you either need separate MeshRenderers on different objects for the different pixels, or you need to be drawing to some kind of dynamic texture.