How to to draw texture on object using code

Ok i found a few topics with the same question, but while i have the same (or almost the same) code, it just doesnt show up

Code example

        for (int i = 0; i < 1024; i++)
            for (int j = 0; j < 512; j++)
            {
                Color c = new Color();
                c = new Color(Random.Range(0,1), Random.Range(0, 1), Random.Range(0, 1));
                tx.SetPixel(i, j, c);
            }
        GetComponent<Renderer>().material.mainTexture = tx;

Generation code for texture is different, but it doesnt matter for now. Script linked to the sphere if i did everything right. Also how do i get some object nd work with it by its id? Considering it has been created earlier

For the texture not showing up: You have to call tx.Apply() after setting the pixels (Texture2D.Apply())

@saschandroid thanks, its amazing how it never mentioned anywhere